text
stringlengths
240
2.92M
meta
dict
Passage 1: Thomas Newman Thomas Montgomery Newman (born October 20, 1955) is an American composer best known for his many film scores. Passage 2: Beauty and the Beast (1991 soundtrack) Beauty and the Beast: Original Motion Picture Soundtrack is the official soundtrack album to the 1991 Disney animated feature film, "Beauty and the Beast". Originally released on October 29, 1991, by Walt Disney Records, the album's first half – tracks 2 to 9 – generally contains the film's musical numbers, all of which were written by composer Alan Menken and lyricist Howard Ashman, while its latter half – tracks 10 to 14 – features its musical score, composed solely by Menken. While the majority of the album's content remains within the musical theatre genre, its songs have also been influenced by French, classical, pop and Broadway music. Credited to Various Artists, "Beauty and the Beast: Original Motion Picture Soundtrack" features performances by the film's main cast – Paige O'Hara, Richard White, Jesse Corti, Jerry Orbach, Angela Lansbury and Robby Benson – in order of appearance. Additionally, the album features recording artists Celine Dion and Peabo Bryson, who perform a pop rendition of the film's title and theme song, "Beauty and the Beast", which simultaneously serves as the soundtrack's only single. Passage 3: 22 Jump Street (Original Motion Picture Score) 22 Jump Street (Original Motion Picture Score) is the official score album for the 2014 Columbia Pictures film "22 Jump Street" featuring music by composer Mark Mothersbaugh. The album was first released by La La Land Records on September 23, 2014 as part of a limited edition 2-CD set which also featured score from 2012 film "21 Jump Street". The "22 Jump Street" score album was later released digitally as a standalone album by Madison Gate Records. Passage 4: The Fate of the Furious (score) The Fate of the Furious: Original Motion Picture Score is the original film score album of the 2017 action film of the same name. It was released by the Universal Music Group on April 28, 2017. The score was written and composed by Brian Tyler, who also wrote and composed the musical score for the third, fourth, fifth and seventh installments. Passage 5: American Beauty: Original Motion Picture Score American Beauty: Original Motion Picture Score is the original score for the 1999 film composed by Thomas Newman. Passage 6: Iron Eagle (soundtrack) Iron Eagle: Original Motion Picture Soundtrack is the soundtrack for the TriStar Pictures film "Iron Eagle", released on July 23, 1986 by Capitol Records. A separate film score by Basil Poledouris titled Iron Eagle: Original Motion Picture Score was released on July 9, 2008 by Varèse Sarabande. Passage 7: The Punisher (1989 score) The Punisher, also known as The Punisher Original Motion Picture Score is the score to the 1989 film of the same name. The album was composed, orchestrated and conducted by Dennis Dreith. It was released on July 19, 2005 on CD, it also features a 23 minutes interview with composer Dreith and the director Mark Goldblatt. The interview focuses not only on the music itself but also much about the ill-fated circumstances which concerned the release of the original film. Passage 8: Batman Forever (score) Batman Forever: Original Motion Picture Score Album is a 1995 Grammy nominated film score album for "Batman Forever", composed by Elliot Goldenthal. It was released in conjunction with its soundtrack counterpart. Despite Goldenthal having recorded over 2 hours of music, the soundtrack only had 45 minutes before La-La Land Records released an expanded version in 2012. The score features big brass, strings and discordant noises while maintaining an anthemic sound. Regarding the villainous leitmotifs, Goldenthal said Two-Face focuses on paired notes and doubled beats while being inspired by Russian composers such as Sergei Prokofiev and Dmitri Shostakovich, and Riddler has a sound reminiscent of old science fiction B-movies with a theremin. On the U2 single "Hold Me, Thrill Me, Kiss Me, Kill Me", there is a track titled "Theme from "Batman Forever"" composed by Goldenthal; this can also be found on the expanded release issued in 2012. Passage 9: Small Soldiers (soundtrack) Small Soldiers (Music from the Motion Picture) and Small Soldiers (Original Motion Picture Score) are the soundtrack and score to the film "Small Soldiers". Passage 10: Batman (score) Batman: Original Motion Picture Score is the score album for the 1989 film "Batman" by Danny Elfman. According to the "Batman" DVD Special Edition, Elfman said that producer Jon Peters was not sure about him as a composer until Tim Burton made him play the main titles. Elfman admitted he was stunned when Peters announced that the score would be released on its own album, as releasing a separate score album for a film was something that was rarely done in the 1980s. Elfman's "The Batman Theme" went on to become an iconic piece. It served as the basis for the theme music of "", which premiered in 1992, although this was later changed. Some parts of the Elfman score are also heard in "", "" and "". Parts are also played in the queue, and on the station platform of Batman the Ride at various Six Flags theme parks. Question: American Beauty: Original Motion Picture Score was composed bu what American composer born in 1955 Answer: Thomas Newman
{ "task_name": "hotpotqa" }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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. */ using System; using System.Globalization; using System.IO; using System.Linq; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders.Fees; using QuantConnect.Util; namespace QuantConnect.Securities.Future { /// <summary> /// Represents a simple margin model for margin futures. Margin file contains Initial and Maintenance margins /// </summary> public class FutureMarginModel : SecurityMarginModel { private static readonly object DataFolderSymbolLock = new object(); // historical database of margin requirements private MarginRequirementsEntry[] _marginRequirementsHistory; private int _marginCurrentIndex; private readonly Security _security; private IDataProvider _dataProvider = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider")); /// <summary> /// True will enable usage of intraday margins. /// </summary> /// <remarks>Disabled by default. Note that intraday margins are less than overnight margins /// and could lead to margin calls</remarks> public bool EnableIntradayMargins { get; set; } /// <summary> /// Initial Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal InitialOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialOvernight ?? 0m; /// <summary> /// Maintenance Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceOvernight ?? 0m; /// <summary> /// Initial Intraday margin for the contract effective from the date of change /// </summary> public virtual decimal InitialIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialIntraday ?? 0m; /// <summary> /// Maintenance Intraday margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceIntraday ?? 0m; /// <summary> /// Initializes a new instance of the <see cref="FutureMarginModel"/> /// </summary> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required unused buying power for the account.</param> /// <param name="security">The security that this model belongs to</param> public FutureMarginModel(decimal requiredFreeBuyingPowerPercent = 0, Security security = null) { RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; _security = security; } /// <summary> /// Gets the current leverage of the security /// </summary> /// <param name="security">The security to get leverage for</param> /// <returns>The current leverage in the security</returns> public override decimal GetLeverage(Security security) { return 1; } /// <summary> /// Sets the leverage for the applicable securities, i.e, futures /// </summary> /// <remarks> /// This is added to maintain backwards compatibility with the old margin/leverage system /// </remarks> /// <param name="security"></param> /// <param name="leverage">The new leverage</param> public override void SetLeverage(Security security, decimal leverage) { // Futures are leveraged products and different leverage cannot be set by user. throw new InvalidOperationException("Futures are leveraged products and different leverage cannot be set by user"); } /// <summary> /// Get the maximum market order quantity to obtain a position with a given buying power percentage. /// Will not take into account free buying power. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the target signed buying power percentage</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { if (Math.Abs(parameters.TargetBuyingPower) > 1) { throw new InvalidOperationException( "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); } return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } /// <summary> /// Gets the total margin required to execute the specified order in units of the account currency including fees /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>The total margin in terms of the currency quoted in the order</returns> public override InitialMargin GetInitialMarginRequiredForOrder( InitialMarginRequiredForOrderParameters parameters ) { //Get the order value from the non-abstract order classes (MarketOrder, LimitOrder, StopMarketOrder) //Market order is approximated from the current security price and set in the MarketOrder Method in QCAlgorithm. var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, parameters.Order)).Value; var feesInAccountCurrency = parameters.CurrencyConverter. ConvertToAccountCurrency(fees).Amount; var orderMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Order.Quantity); return new InitialMargin(orderMargin + Math.Sign(orderMargin) * feesInAccountCurrency); } /// <summary> /// Gets the margin currently allotted to the specified holding /// </summary> /// <param name="parameters">An object containing the security</param> /// <returns>The maintenance margin required for the </returns> public override MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { var security = parameters.Security; if (security?.GetLastData() == null || parameters.Quantity == 0m) { return 0m; } var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return marginReq.MaintenanceIntraday * parameters.AbsoluteQuantity; } // margin is per contract return marginReq.MaintenanceOvernight * parameters.AbsoluteQuantity; } /// <summary> /// The margin that must be held in order to increase the position by the provided quantity /// </summary> public override InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { var security = parameters.Security; var quantity = parameters.Quantity; if (security?.GetLastData() == null || quantity == 0m) return InitialMargin.Zero; var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return new InitialMargin(marginReq.InitialIntraday * quantity); } // margin is per contract return new InitialMargin(marginReq.InitialOvernight * quantity); } private MarginRequirementsEntry GetCurrentMarginRequirements(Security security) { if (security?.GetLastData() == null) return null; if (_marginRequirementsHistory == null) { _marginRequirementsHistory = LoadMarginRequirementsHistory(security.Symbol); _marginCurrentIndex = 0; } var date = security.GetLastData().Time.Date; while (_marginCurrentIndex + 1 < _marginRequirementsHistory.Length && _marginRequirementsHistory[_marginCurrentIndex + 1].Date <= date) { _marginCurrentIndex++; } return _marginRequirementsHistory[_marginCurrentIndex]; } /// <summary> /// Gets the sorted list of historical margin changes produced by reading in the margin requirements /// data found in /Data/symbol-margin/ /// </summary> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] LoadMarginRequirementsHistory(Symbol symbol) { var directory = Path.Combine(Globals.DataFolder, symbol.SecurityType.ToLower(), symbol.ID.Market.ToLowerInvariant(), "margins"); return FromCsvFile(Path.Combine(directory, symbol.ID.Symbol + ".csv")); } /// <summary> /// Reads margin requirements file and returns a sorted list of historical margin changes /// </summary> /// <param name="file">The csv file to be read</param> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] FromCsvFile(string file) { lock (DataFolderSymbolLock) { // skip the first header line, also skip #'s as these are comment lines var marginRequirementsEntries = _dataProvider.ReadLines(file) .Where(x => !x.StartsWith("#") && !string.IsNullOrWhiteSpace(x)) .Skip(1) .Select(MarginRequirementsEntry.Create) .OrderBy(x => x.Date) .ToArray(); if(marginRequirementsEntries.Length == 0) { Log.Trace($"Unable to locate future margin requirements file. Defaulting to zero margin for this symbol. File: {file}"); return new[] { new MarginRequirementsEntry { Date = DateTime.MinValue } }; } return marginRequirementsEntries; } } } }
{ "task_name": "lcc" }
Document: 15 Minutes with A.O. Scott Before presenting at the Harvard Book Store, Scott chatted with FM about topics ranging from his book and Rotten Tomatoes to #OscarsSoWhite and “Freddy got Fingered.” Shortly after this year’s Academy Awards, New York Times film critic A.O. Scott ’87-’88 visited Harvard Square to promote his new book, “Better Living Through Criticism.” The book, Scott’s first, addresses the role of critics and criticism in the process of creating art. Before presenting at the Harvard Book Store, Scott chatted with FM about topics ranging from his book and Rotten Tomatoes to #OscarsSoWhite and “Freddy got Fingered.” FM: In your book, you argue that criticism is imperative to the creative process. What exactly do you mean by this? S: First of all, the perspective that art takes on the world is inherently a critical one, one that is looking for value, one that is interpreting. I think it’s also true that most art is engaged explicitly or implicitly with other art; that is, artists are inspired by or are trying to imitate, or correct, or improve upon, or understand the work that surrounds them. So criticism is really built into a great deal of what artists do, even at the level of technique, but also at the level of thinking. FM: Do you think the creation of art is then filtered through this criticism process? S: I think it is. You know, when you listen to the Rolling Stones, and you hear Muddy Waters, or when you look at a Tarantino movie and you see what he’s doing with Blaxploitation films, what you’re watching is a work of criticism. FM: Do you think that your criticism as a New York Times film critic impacts the field? S: I have no idea. FM: That’s fair. S: In a way, it’s not for me to say. It’s not quite my intention. It’s certainly true that people who are involved in film do read the works of critics, but I’m not sure there’s a direct influence. And I don’t think that it’s necessarily the role of the critic to prescribe what artists do. It’s more the work of critics to try to do some work on behalf of the audience in evaluating and understanding artists’ work. FM: In a similar vein, the phrase “everyone’s a critic” seems especially relevant today, because everyone has an outlet to express their opinions, be it via blogs or through Twitter. How do you view this change in the media landscape? S: I think it’s a change in the media platforms that are available for people to express and exchange their opinions. I’m actually not sure it’s a huge change in what criticism is and how it works. I think people have always been reacting to what they see, arguing about it, developing their opinions with more or less rigor or discipline. I think what has changed is that now there is a medium available for the exchange to happen in public and across a much wider, larger public than before. FM: I would imagine that people today have shortened attention spans, as flashy headlines and sound bites will drive more clicks and reads than long, in-depth articles. Do you think this has affected your role as a critic? S: I don’t know. The attention span is a mysterious thing. On the one hand, it’s often said that people have short or fragmented attention spans. On the other hand, people will binge watch like 17 hours of a TV show in one weekend. The reviews that are published in The New York Times are substantially longer than they were 30 or 40 years ago. The major reviews of the major movies tend to be 900 or a 1,000 words and that’s partly because our readership seems to want a little more depth and a little more thought. It’s something other than a kind of easy snap judgment or a numerical value that you get on an aggregation site like Rotten Tomatoes. FM: How do you view sites like Rotten Tomatoes as vehicles for criticism? S: Rotten Tomatoes is interesting because it aggregates reviews, so it doesn’t present any kind of argument. There’s nothing in the Rotten Tomatoes raw score, or even the little quotes that they use on the site, that would really persuade you to see a movie or not. It’s just sort of an index of opinion. It’s like a poll. And that can be useful if you want to check in and say, “Oh okay, all of these critics and art people, they mostly liked it.” Whether or not that means you too will like it is another question. I think you can get a better sense of whether or not you think you’re going to like something if you read the work of a critic that you know and trust and tend to understand. FM: Is there a universally panned movie that you have enjoyed more than other critics? S: The most famous one in my career goes back some years to “Freddy Got Fingered,” which is one of the most reviled and hated movies that I can think of. I said it was a challenging and innovative work of art. It’s a movie directed by and starring Tom Green, who is still around but was a pretty popular MTV host in the late 90s and early 2000’s. He shows up in an Eminem song “The Real Slim Shady,” where it talks about him humping a dead moose on MTV. He made this movie that is fairly extreme, even by current standards of gross humor, but I thought it was conceptually and formally brilliant. So I wrote a fairly notorious rave of it, but every other review was like an F and a one star. There were critics who were claiming to have walked out because they couldn’t stand watching it. So there I was, fairly new at The New York Times, and I did have a moment of, “Oh my gosh, I’m going to get fired.” But nope. FM: Has that film gained a cult following since it was released? S: It has, and I believe I had something to do with it. A couple of years after the movie, people would make fun of the fact that I liked it. Now, every once in awhile, someone will come up on Twitter and pat me on the back, so the status of that review has slipped over time. It’s now not so much mocked, but held up as one of my better efforts. FM: On the flipside, are there any universally praised movies that you very much disliked? S: Yeah, I was not a big fan of “The Theory of Everything” or of Eddie Redmayne’s performance in it. I remember fairly early on, I panned “Wonder Boys,” and I panned “Erin Brockovich.” I stand by those. I had a lot of problems with “Son of Saul,” which recently won the Oscar for Best Foreign Language Film, and I wrote up a pretty hard criticism of it. When you pan movies like that, you get a lot of pushback, because those movies are extravagantly praised and represent a sort of seriousness of purpose and artistic ambition. People really don’t like it when critics come out against them. FM: Right, I remember seeing Samuel L. Jackson tweet about your review for “The Avengers,” which he was not so happy about. S: It was a valuable moment in a way, because it helped encourage me in the writing of this book. Usually with movie stars, you kind of leave them alone and don’t want to fight, but he did say that Avengers fans should go help find me a new job, one that I could actually do. And that kind of got me thinking about what a job is, how you actually do it, and that did accelerate the writing of this book. FM: As a film critic, how would you say your role expands to criticism of the film industry? S: Well, I think it’s important. I think it’s very important to understand where movies come from: who makes them, how they’re made. Every movie, however small, represents a rather large and complicated commercial enterprise in a way that a book doesn’t. You are confronted with the facts and artifacts of capitalism every time you are writing about a movie, and you cannot make that the whole subject of your criticism or the whole burden of every review, but you need to be aware of it, and sometimes you need to remind your viewers of it. FM: What then do you think is the biggest issue in the film industry right now that should be addressed? S: I think in the American film industry, there is no question that it is increasing diversity. #OscarsSoWhite was pointing out a very particular manifestation of a very broad, systemic problem, and I think the really shocking, dramatic exclusion of women and people of color from all aspects of the industry is the thing that the industry is going to have to deal with. That’s the big one, and I think some of us have been trying to call attention to that for a while. It’s definitely not going to end because the Oscars are over and Chris Rock made everyone laugh about it. ||||| 0 Concord man accused of not returning VHS rental 14 years later CONCORD, N.C. - A Concord man was arrested for failing to return a 2002 VHS rental movie, “Freddy Got Fingered.” James Meyers showed Channel 9 the arrest warrant Wednesday. It shows Meyers is charged with failure to return rental property, a misdemeanor punishable by a fine of up to $200. The charged had not been dismissed as of Wednesday afternoon. The story of Meyers' arrest has since gone viral after Eyewitness News broke the news late Wednesday night. The rental store in Salisbury, J&J’s Video, has since closed, but Meyers was still given an April 27 court date for failing to return the gross-out comedy about a cartoonist returning home to live with his parents. (Pictured: James Meyers) Meyers said he was driving his daughter to school on Concord Parkway Tuesday morning when a Concord police officer pulled him over for a tail-light that was out. Meyers said the officer ran his license and approximately 25 minutes later asked him to step out of the vehicle. “The officer said, 'I don’t know how to tell you this but there’s a warrant out for your arrest from 2002. Apparently you rented the movie "Freddy Got Fingered" and never returned it.' I thought he was joking,” said Meyers. Meyers said the officers were very polite and professional. They let him take his daughter to school and go to work as long as he promised to turn himself into the police department later that day. Concord officials said the warrant was active in NCAWARE, which is North Carolina's electronic warrant repository. It was signed on Feb. 28, 2002 by J&J Video and was a vaild Rowan County arrest warrant for failing to return rental property. Meyers said he thought everything would get straightened out at the department. He was surprised when officers arrested him and then took him to the magistrate’s office. “For the first time I got put in handcuffs,” said Meyers. Officers are required by police to handcuff anyone in custody before entering the secured area inside the magistrate's office, Concord officials told Channel 9. Meyers said he vaguely remembers renting the particular movie from the family-owned video store in Kannapolis. I just saw this and I am struggling to believe it is real. https://t.co/GrTXoUj29X — Tom Green (@tomgreenlive) March 24, 2016 The 2001 movie “Freddy Got Fingered” starred comedian Tom Green. On Wednesday night, Meyers received a call from Green, the writer-director-star of “Freddy” who reached out after Meyers’ friend shared the story with him on Twitter, according to The New York Daily News. Green, who is currently on a stand-up comedy tour in Australia, told the Daily News that he is happy to support fans of his film, which was the subject of terrible reviews and currently has an 11 percent rating on Rotten Tomatoes. In the video below, Green talked about the incident on the Australian TV show "The Project." "I think it's sort of an example of how bureaucracy can get out of control," Green said during the program. (Scroll to 2:40 mark it the video) Tom Green We chat to Tom Green about social media, koalas & the man who was arrested for not returning a VHS of 'Freddy Got Fingered'! #TheProjectTV Posted by The Project on Thursday, March 24, 2016 The 44-year-old comedian told the Daily News that he could put in a good word with the court or even help out financially as long as the outcome doesn’t involve an outrageous sum. “If it’s 200 bucks of course I’ll pay it for him, just for the principle of the thing,” Green said. Meyers told Channel 9 he can only hope the charges get dismissed. He added that he had been pulled over since the warrant was issued in 2002, but had never heard about the lost tape. “They’re not focusing on the crimes I think they should be focusing on,” Meyers said. “That hour the cops sat out there with me, the hour and a half I was down in the magistrate's office, could have been spent somewhere else.” (Tom Green in "Freddy Got Fingered." Photo: Getty) It's not the first time such a case has happened. In 2014, a woman was arrested in Pickens County, South Carolina, for failing to return a rental. The charges were later dropped. "This would be a case that you would dismiss," said John Snyder, an attorney and former District Attorney for Union County. Snyder said officers were simply following the law by making the arrest. "Officers can't not arrest them and that's the issue," Snyder said. Snyder said people ought to check and see if there is a warrant out for them, just like a credit check. Eyewitness News spoke with the Rowan County District Attorney but she was unable to comment because it is a pending case. Eyewitness News also tried contacting the person who filed for the warrant on behalf of the now-closed business but was unsuccessful. Read our follow-up coverage on this viral story: © 2018 Cox Media Group. ||||| These crawls are part of an effort to archive pages as they are created and archive the pages that they refer to. That way, as the pages that are referenced are changed or taken from the web, a link to the version that was live when the page was written will be preserved.Then the Internet Archive hopes that references to these archived pages will be put in place of a link that would be otherwise be broken, or a companion link to allow people to see what was originally intended by a page's authors.The goal is to fix all broken links on the web . Crawls of supported "No More 404" sites. ||||| The final credits of "Freddy Got Fingered," and its redundant but obligatory outtakes, roll to the sound of Eminem's white-boy hip-hop anthem "The Real Slim Shady," which includes a reference to this movie's director, star and co-writer. Why, the rapper asks (and here I must paraphrase), do people take offense at his lyrics when Tom Green can, with apparent impunity, violate a dead moose on MTV? It's a fair enough question, if somewhat disingenuous. Eminem and Mr. Green, who rose to fame as the creator and host of a prank-driven show on that cable channel, share a taste (if that's the right word) for confrontational shock tactics. And they have become, not entirely against their will, fodder for the latest round of pious hand wringing about the state of youth-oriented pop culture for their brazen affronts to decency and propriety. But forget about all that for a moment. For the record, no dead moose appears in "Freddy Got Fingered," though Mr. Green does stimulate a live elephant and a lusty stallion, decks himself out shaman style in the bloody hide of a road- killed buck and wears a human umbilical cord duct-taped to his navel. Still, just as Eminem disarms anyone who bothers to listen to his songs (rather than quoting them secondhand for the purposes of punditry) with his verbal wit and rhythmic dexterity, so does Mr. Green stage his gross-outs with a demented but unmistakable integrity. Like it or not, he's an artist. At the screening of "Freddy Got Fingered" I attended, a number of viewers clearly chose not, sweeping down the aisles with their coats flapping behind them like agitated bats. The scene that provoked the largest exodus was one in which Mr. Green's character, Gord Brody, a 28-year-old aspiring cartoonist living in his parents' basement, delivers a child, severs the umbilicus with his teeth and then swings the baby over his head before tenderly handing it to the stunned, blood-spattered mother. ("I saved the day," he declares as he is escorted from the hospital.) This was, I have to say, a bit much, as were the several gruesome injuries visited on a perky young boy with the misfortune to be Gord's neighbor and the subplot in which Gord falsely accuses his father (Rip Torn) of molesting Gord's younger brother Freddy (who is 25). If you were wondering about the meaning of the film's title, now you know. So consider yourself sufficiently warned. Hear me out, though, because I come not to bury Mr. Green but — guardedly and with a slightly guilty conscience — to praise him. Like the unjustly maligned and neglected "Monkeybone," this much- hyped picture is in danger of being dismissed as yet another exercise in dumbed-down toilet humor. But to throw it into the refuse pile along with "Saving Silverman," "Say It Isn't So" and "Tomcats" would be to underestimate Mr. Green's originality and to misconstrue his intentions. In a recent article in Entertainment Weekly, Mr. Green boasted (and again I must paraphrase) about the absence of excremental and flatulent humor in his movie. The standard gross-out comedy relies on these elements and combines them with adolescent male sexual panic, as if toilet training and puberty were simultaneous developmental occurrences. Mr. Green's humor is certainly regressive, as film comedy has been at least since Fatty Arbuckle appeared in diapers. But "Freddy Got Fingered" forsakes the muddy field of infantile narcissism for the fertile, frightening ground of middle childhood. It's less about the dangers and pleasures of the unchained id than the giddy anarchy of the unbound imagination. It's scarier than "Scary Movie" and funnier, too. Though Gord dreams of being an animator (and travels from his Oregon home to Los Angeles in the hope of breaking into television), his true métier, like that of his creator, is a kind of pure and audacious conceptual performance art. The movie's comic heart consists of a series of indescribably loopy, elaborately conceived happenings that are at once rigorous and chaotic, idiotic and brilliant. Some of these — the "backwards man" bit, the sausage-piano concert and the fake cell phone in the restaurant scene — might have qualified for a grant from the National Endowment for the Arts if MTV and studio money hadn't been forthcoming and may show up some day at the Museum of Modern Art. Like any mature artist, Mr. Green bows to the traditions that fed him while refusing mere imitation. His love interest, Betty, is a paraplegic (and an amateur rocket scientist) whose sexual interests include being whacked on the shins with a bamboo cane. Their romance owes something to the kinky humanism of John Waters and the Farrelly brothers, and Gord himself could be the younger brother of the overgrown paper boy from "Get a Life," Chris Elliott's sitcom from the cheesy golden age of Fox television. Mr. Green's style, toggling between antic and deadpan, is like a less hostile version of the work Michael O'Donoghue and Andy Kaufman did in the early days of "Saturday Night Live." Mr. Green is less an actor than a persona, and he resolutely refuses to mark the boundaries of his imposture or to resort to the winking, supercilious pseudo-irony that remains the default setting for so much second-rate pop culture. His assaultive forays into public space pay homage (perhaps inadvertently) to 70's conceptualist pioneers like Bruce Nauman and Vito Acconci, mixing in some of the sweet absurdism of William Wegman before he was captured by "Sesame Street" (and with a preference for wild over domesticated animals). This movie's set pieces, many of which seem to revel in the double meaning of the word gag, are draped over a rickety but serviceable narrative trellis. The core conflict, between Gord and his father, is like something Ingmar Bergman might have written for SCTV. The elder Brody is a ferocious avatar of the work ethic, a dervish of brutality, shame and thwarted tenderness. The casting of Mr. Torn provides a fine piece of visual humor; with his lank hair and goatee he looks like a squashed, dried-out version of Mr. Green. As a director Mr. Green is competent, which is no small achievement, given the lurching sloppiness of so much movie comedy these days. His visual style is as relentless as his personality. In the opening sequence Gord hurtles through a shopping mall on his skateboard as one of Eminem's progenitors, the Sex Pistols' Johnny Rotten, squalls and spits a song called "Problems," a catalog of disaffection whose chorus declares, "The problem is you." This is the gauntlet Mr. Green, genial and repellent, throws down before both his fans and his detractors. You can take it or leave it. (But if you take it, put on some latex gloves and wash up when you're finished. Who knows where it's been?) "Freddy Got Fingered" is rated R (Under 17 requires accompanying parent or adult guardian). See above. FREDDY GOT FINGERED Directed by Tom Green; written by Mr. Green and Derek Harvie; director of photography, Mark Irwin; edited by Jacqueline Cambas; music by Mike Simpson; production designer, Bob Ziembicki; produced by Larry Brezner, Lauren Lloyd and Howard Lapides; released by 20th Century Fox. Running time: 97 minutes. This film is rated R. WITH: Tom Green (Gord Brody), Rip Torn (Jim Brody), Harland Williams (Darren), Julie Hagerty (Julie Brody), Marisa Coughlan (Betty) and Eddie Kaye Thomas (Freddy). Summary: – If you're going to fall into highly publicized trouble for an overdue movie rental, at least hope you're busted for a dusty copy of Citizen Kane. North Carolinian James Meyers wasn't so lucky, Channel 9 reports—not only suffering the embarrassment of getting arrested for failing to return a VHS tape he took out 14 years ago, but also the shame of the movie he rented: 2001's universally panned Freddy Got Fingered, written and directed by and starring Tom Green. Meyers says he was driving his daughter to school Tuesday when he was pulled over for a broken taillight. After the cop ran his license, he asked Meyers to step out of the car. "I don't know how to tell you this, but there's a warrant out for your arrest from 2002," the cop said, per Meyers. "Apparently you rented the movie Freddy Got Fingered and never returned it." Meyers said he thought the officer was kidding, and he was allowed to take his daughter to school by promising to clear it up at the magistrate's office the next day. But when he showed, he was handcuffed and charged with a misdemeanor for failing to return rental property, with a fine up to $200. Green himself heard about Meyers' plight through social media, noting he was "struggling to believe it is real," and the New York Daily News reports that he called Meyers Wednesday to offer moral, and perhaps financial, support. "If it's 200 bucks of course I'll pay it for him, just for the principle of the thing," Green tells the paper. Meyers has an April 27 court date. (One movie critic who holds the movie in high regard: AO Scott of the New York Times.)
{ "task_name": "multi_news" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Microsoft.Cci.Extensions; using Microsoft.Cci.Extensions.CSharp; using Microsoft.Cci.Writers.Syntax; namespace Microsoft.Cci.Writers.CSharp { public partial class CSDeclarationWriter { private void WriteMethodDefinition(IMethodDefinition method) { if (method.IsPropertyOrEventAccessor()) return; if (method.IsDestructor()) { WriteDestructor(method); return; } string name = method.GetMethodName(); WriteMethodPseudoCustomAttributes(method); WriteAttributes(method.Attributes); WriteAttributes(method.SecurityAttributes); if (!method.ContainingTypeDefinition.IsInterface) { if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility); WriteMethodModifiers(method); } WriteInterfaceMethodModifiers(method); WriteMethodDefinitionSignature(method, name); WriteMethodBody(method); } private void WriteDestructor(IMethodDefinition method) { WriteSymbol("~"); WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name); WriteSymbol("("); WriteSymbol(")", false); WriteEmptyBody(); } private void WriteTypeName(ITypeReference type, ITypeReference containingType, bool isDynamic = false) { var useKeywords = containingType.GetTypeName() != type.GetTypeName(); WriteTypeName(type, isDynamic: isDynamic, useTypeKeywords: useKeywords); } private void WriteMethodDefinitionSignature(IMethodDefinition method, string name) { bool isOperator = method.IsConversionOperator(); if (!isOperator && !method.IsConstructor) { WriteAttributes(method.ReturnValueAttributes, true); // We are ignoring custom modifiers right now, we might need to add them later. WriteTypeName(method.Type, method.ContainingType, isDynamic: IsDynamic(method.ReturnValueAttributes)); } WriteIdentifier(name); if (isOperator) { WriteSpace(); WriteTypeName(method.Type, method.ContainingType); } Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances"); if (method.IsGeneric) WriteGenericParameters(method.GenericParameters); WriteParameters(method.Parameters, method.ContainingType, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments); if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod()) WriteGenericContraints(method.GenericParameters); } private void WriteParameters(IEnumerable<IParameterDefinition> parameters, ITypeReference containingType, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false) { string start = property ? "[" : "("; string end = property ? "]" : ")"; WriteSymbol(start); _writer.WriteList(parameters, p => { WriteParameter(p, containingType, extensionMethod); extensionMethod = false; }); if (acceptsExtraArguments) { if (parameters.Any()) _writer.WriteSymbol(","); _writer.WriteSpace(); _writer.Write("__arglist"); } WriteSymbol(end); } private void WriteParameter(IParameterDefinition parameter, ITypeReference containingType, bool extensionMethod) { WriteAttributes(parameter.Attributes, true); if (extensionMethod) WriteKeyword("this"); if (parameter.IsParameterArray) WriteKeyword("params"); if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference) { WriteKeyword("out"); } else { // For In/Out we should not emit them until we find a scenario that is needs thems. //if (parameter.IsIn) // WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true); //if (parameter.IsOut) // WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true); if (parameter.IsByReference) WriteKeyword("ref"); } WriteTypeName(parameter.Type, containingType, isDynamic: IsDynamic(parameter.Attributes)); WriteIdentifier(parameter.Name); if (parameter.IsOptional && parameter.HasDefaultValue) { WriteSymbol("="); WriteMetadataConstant(parameter.DefaultValue, parameter.Type); } } private void WriteInterfaceMethodModifiers(IMethodDefinition method) { if (method.GetHiddenBaseMethod(_filter) != Dummy.Method) WriteKeyword("new"); } private void WriteMethodModifiers(IMethodDefinition method) { if (method.IsMethodUnsafe()) WriteKeyword("unsafe"); if (method.IsStatic) WriteKeyword("static"); if (method.IsPlatformInvoke) WriteKeyword("extern"); if (method.IsVirtual) { if (method.IsNewSlot) { if (method.IsAbstract) WriteKeyword("abstract"); else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots WriteKeyword("virtual"); } else { if (method.IsAbstract) WriteKeyword("abstract"); else if (method.IsSealed) WriteKeyword("sealed"); WriteKeyword("override"); } } } private void WriteMethodBody(IMethodDefinition method) { if (method.IsAbstract || !_forCompilation || method.IsPlatformInvoke) { WriteSymbol(";"); return; } if (method.IsConstructor) WriteBaseConstructorCall(method.ContainingTypeDefinition); // Write Dummy Body WriteSpace(); WriteSymbol("{", true); WriteOutParameterInitializations(method); if (_forCompilationThrowPlatformNotSupported) { Write("throw new "); if (_forCompilationIncludeGlobalprefix) Write("global::"); Write("System.PlatformNotSupportedException(); "); } else if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor) { // Structs cannot have empty constructors so we need to output this dummy body Write("throw null;"); } else if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid)) { WriteKeyword("throw null;"); } WriteSymbol("}"); } private void WritePrivateConstructor(ITypeDefinition type) { if (!_forCompilation || type.IsInterface || type.IsEnum || type.IsDelegate || type.IsValueType || type.IsStatic) return; WriteVisibility(TypeMemberVisibility.Assembly); WriteIdentifier(((INamedEntity)type).Name); WriteSymbol("("); WriteSymbol(")"); WriteBaseConstructorCall(type); WriteEmptyBody(); } private void WriteOutParameterInitializations(IMethodDefinition method) { if (!_forCompilation) return; var outParams = method.Parameters.Where(p => p.IsOut); foreach (var param in outParams) { WriteIdentifier(param.Name); WriteSpace(); WriteSymbol("=", true); WriteDefaultOf(param.Type); WriteSymbol(";", true); } } private void WriteBaseConstructorCall(ITypeDefinition type) { if (!_forCompilation) return; ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull(); if (baseType == null) return; var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m)); var defaultCtor = ctors.Where(c => c.ParameterCount == 0); // Don't need a base call if we have a default constructor if (defaultCtor.Any()) return; var ctor = ctors.FirstOrDefault(); if (ctor == null) return; WriteSpace(); WriteSymbol(":", true); WriteKeyword("base"); WriteSymbol("("); _writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type)); WriteSymbol(")"); } private void WriteEmptyBody() { if (!_forCompilation) { WriteSymbol(";"); } else { WriteSpace(); WriteSymbol("{", true); WriteSymbol("}"); } } private void WriteDefaultOf(ITypeReference type) { WriteKeyword("default", true); WriteSymbol("("); WriteTypeName(type, true); WriteSymbol(")"); } public static IDefinition GetDummyConstructor(ITypeDefinition type) { return new DummyInternalConstructor() { ContainingType = type }; } private class DummyInternalConstructor : IDefinition { public ITypeDefinition ContainingType { get; set; } public IEnumerable<ICustomAttribute> Attributes { get { throw new System.NotImplementedException(); } } public void Dispatch(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } public IEnumerable<ILocation> Locations { get { throw new System.NotImplementedException(); } } public void DispatchAsReference(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } } } }
{ "task_name": "lcc" }
Document: Image copyright EPA/ Yulia Skripal/Facebook Image caption Sergei Skripal, 66, and his daughter Yulia, 33, are in a critical condition in hospital Former spy Sergei Skripal and his daughter were poisoned by a military-grade nerve agent of a type developed by Russia, Theresa May has told MPs. The PM said it was "highly likely" Russia was responsible for the Salisbury attack. The Foreign Office summoned Russia's ambassador to provide an explanation. Mrs May said if there is no "credible response" by the end of Tuesday, the UK would conclude there has been an "unlawful use of force" by Moscow. The chemical used in the attack, the PM said, has been identified as one of a group of nerve agents known as Novichok. Mrs May said: "Either this was a direct action by the Russian state against our country, or the Russian government lost control of its potentially catastrophically damaging nerve agent and allowed it to get into the hands of others." Media playback is unsupported on your device Media caption Theresa May: Spy poisoned by "military-grade nerve agent" She said Foreign Secretary Boris Johnson had told the ambassador Moscow must provide "full and complete disclosure" of the Novichok programme to international body the Organisation for the Prohibition of Chemical Weapons. Mrs May said the UK must stand ready to take much more extensive measures, and these would be set out in the Commons on Wednesday should there be no adequate explanation from Russia. Retired military intelligence officer Mr Skripal, 66, and his daughter, Yulia, 33, were found slumped on a bench in Salisbury city centre on Sunday 4 March. They remain in a critical but stable condition in hospital. Det Sgt Nick Bailey, who fell ill attending the pair, remains seriously ill, but has been talking to his family. Mr Skripal was convicted by the Russian government of passing secrets to MI6 in 2004, but given refuge in the UK in 2010 as part of a "spy swap". Home Secretary Amber Rudd will chair a meeting of the government emergency committee Cobra on Tuesday to discuss the latest developments in the case. What are Novichok agents? Image copyright PA Image caption Investigators removed a vehicle from a village near Salisbury on Monday The name means "newcomer" in Russian, and applies to a group of advanced nerve agents developed in secret by the Soviet Union in the 1970s and 1980s One chemical - called A-230 - is reportedly five to eight times more toxic than VX nerve agent, which can kill a person within minutes Some are liquids, others are thought to exist in solid form. Some are reported to be "binary weapons", meaning they are typically stored as two less toxic chemicals which when mixed, react to produce the more toxic agent One variant was reportedly approved for use by the Russian military as a chemical weapon Designed to escape detection by international inspectors, their existence was revealed by defectors Read more on Novichok and what it can do Addressing the Commons following a meeting of the government's National Security Council, Mrs May said: "This attempted murder using a weapons-grade nerve agent in a British town was not just a crime against the Skripals. "It was an indiscriminate and reckless act against the United Kingdom, putting the lives of innocent civilians at risk." She told MPs the positive identification of this chemical agent was made by experts at the UK's Porton Down laboratory. She said Russia has previously produced the agent and would still be capable of doing so. The decision to point the finger at Moscow was also based on "Russia's record of conducting state-sponsored assassinations and our assessment that Russia views some defectors as legitimate targets for assassinations", the PM added. Media playback is unsupported on your device Media caption Jeremy Corbyn urges action - but criticises the Tories for taking donations from "Russian oligarchs" Labour leader Jeremy Corbyn said "robust dialogue" with Russia was needed to avoid escalating tensions further - but he was heckled by Tory MPs when he raised questions about Russian oligarchs donating money to the Conservatives. 'Circus show' Secretary of State Rex Tillerson said the US agreed with the UK that Russia was likely to be behind the attack. "We agree that those responsible - both those who committed the crime and those who ordered it - must face appropriately serious consequences," he added. "We stand in solidarity with our allies in the United Kingdom and will continue to coordinate closely our responses." Mrs May spoke to French President Emmanuel Macron on Monday and "discussed the wide pattern of aggressive Russian behaviour and agreed that it would be important to continue to act in concert with allies to address it", her spokesman said. Nato Secretary General Jens Stoltenberg said the use of any nerve agent was "horrendous and completely unacceptable" and officials were in touch with the UK. Downing Street said the incident was not an "article five" matter - a reference to Nato rules which say an attack on one member constitutes an attack on all. However, the former UK National Security Adviser Lord Ricketts said action would be more effective with a "broader, Nato-EU solidarity behind us". He added: "We can't out-punch Putin... But we can take a stand and we can invite others to join us." Media playback is unsupported on your device Media caption Vladimir Putin is challenged by the BBC over the Skripal poisoning Russian Foreign Ministry spokeswoman Maria Zakharova said Mrs May's statement was "a circus show in the British parliament". "The conclusion is obvious - it's another information and political campaign based on provocation," she said. Earlier, asked whether Russia was to blame, President Vladimir Putin told the BBC: "Get to the bottom of things there, then we'll discuss this." BBC political editor Laura Kuenssberg says the tone of the meeting between Boris Johnson and the Russian ambassador Alexander Yakovenko was "cool but firm". She says the men did not shake hands and the foreign secretary expressed the "outrage" of the British public. What will the PM do next? By James Landale, diplomatic correspondent Theresa May could have thrown the kitchen sink at Russia, expelling diplomats, toughening sanctions, and cracking down on oligarchs who keep their cash in London. Instead, the PM has chosen a staged response, throwing down an ultimatum to the Kremlin to explain what happened or face the consequences. The argument she was making was that this attack crossed a line, that it was not the sort of thing that sometimes happens to old spies in the darker underbelly of the intelligence world, but instead it was part of a pattern of Russian aggression from which other countries have also suffered. The question now is what action Mrs May will be prepared to take on Wednesday once Russia has responded, or perhaps failed to respond. The key will be the scale of the international co-operation she can secure. For it is one thing to crack down on wealthy Russians in London, but it is another to secure united international action against Moscow. This is a tougher ask, particularly when President Trump has yet to comment on the Salisbury attack and many European partners are looking to soften existing sanctions against Russia. Mrs May is promising "extensive measures" - the question will be whether they will be enough to make the Kremlin think twice. Police and Army activity continued in the Salisbury area on Monday, with officers - some wearing hazardous materials suits - removing a white van from the village of Winterslow, about six miles away. A Sainsbury's car park has become the latest area to be sealed off in the city itself. Mrs May said the people of Salisbury had responded with "fortitude and calmness", but there was some concern among residents about the length of time it had taken for information to be released. On Sunday, up to 500 Salisbury pub-goers and diners were told to wash their possessions as a precaution after trace amounts of the substance used to poison Sergei and Yulia Skripal were found on and around a table where they had eaten in Zizzi. Traces were also found at the Mill pub in the city which, like Zizzi, remains closed. Graham Mulcock, who saw the Skripals being treated by paramedics in the street, said it was a "disappointment" that advice which "might affect people" was not released sooner. Former chief medical officer for England, Sir Liam Donaldson, said he had also been a "little surprised" that communication with the public had been "slow to get off the ground". Meanwhile, a man from Salisbury who breached the cordon around the bench where Mr Skripal and his daughter were found has been jailed for 16 weeks. Father-of-three Jamie Knight, 30, who pleaded guilty to assault, criminal damage and racially aggravated public disorder, was said to have been drunk when he shouted out abusive remarks about Russians, Swindon Magistrates' Court was told. ||||| Military personnel in College Street Car Park in Salisbury, Sunday March 11, 2018, as police and members of the armed forces probe the suspected nerve agent attack on Russian double agent Sergei Skripal,... (Associated Press) Military personnel in College Street Car Park in Salisbury, Sunday March 11, 2018, as police and members of the armed forces probe the suspected nerve agent attack on Russian double agent Sergei Skripal, which took place on Sunday March 4. British health authorities said Sunday that small traces of... (Associated Press) LONDON (AP) — The Latest on the poisoning of a former Russian spy and his daughter in Britain (all times local): 5:10 p.m. British Prime Minister Theresa May says the Russian ex-spy poisoned in England was exposed to a military-grade nerve agent of type produced by Russia May told lawmakers during an address in parliament on Monday it was "highly likely' Russia was responsible for poisoning Sergei Skripal, the former Russian military intelligence officer who was convicted of spying for Britain. May says Russia's ambassador to the U.K. has been summoned to explain how a Russian nerve agent turned up in Salisbury, the English city where Skripal and his adult daughter were sickened. The British prime minister says if Moscow is proven to be behind the poisoning, her government will consider it an "unlawful use of force" by Russia. ___ 2:20 p.m. Russian President Vladimir Putin says Britain should figure out what happened to ex-spy Sergei Skripal before blaming the poisoning on Russia. Asked by a British reporter in southern Russia if Russia was behind the poisoning, Putin said in comments carried by Russian news wires on Monday: "You first get to the bottom of things over there, and after that we can discuss it." Skripal is a former Russian military intelligence officer who was convicted of spying in Britain and released from prison as part of a spy swap. He and his daughter remain in critical condition following the March 4 nerve agent attack in England. Authorities haven't said what nerve agent was used. British Prime Minister Theresa May is expected to update lawmakers later Monday on the case. ___ 11:40 a.m. The Kremlin has rejected suggestions that it might be behind the poisoning of an ex-Russian spy and his daughter that has left them in critical condition. Dmitry Peskov, spokesman for President Vladimir Putin, told reporters that Sergei Skripal worked for British intelligence and was poisoned on British soil, and therefore the incident "has nothing to do with Russia, let alone the Russian leadership." Peskov also said the Kremlin has not heard any official statements of Russian involvement. Earlier Monday, senior British lawmaker Tom Tugendhat told the BBC the March 4 poisoning of Skripal and his daughter Yulia is looking "like it was state-sponsored attempted murder." The British prime minister is chairing a National Security Council meeting later on Monday to hear the latest evidence. ___ 9:10 a.m. A senior British lawmaker says the poisoning of ex-spy Sergei Skripal and his daughter is "looking awfully like it was state-sponsored attempted murder." Tom Tugendhat told the BBC it is still too early to be absolutely certain. The chairman of the Foreign Affairs committee said he would be "surprised" if Prime Minister Theresa May does not end up blaming Russian officials for the attack. He says the announcement may come soon. May is chairing a National Security Council meeting Monday to hear the latest evidence. Skripal and his daughter Yulia remain in critical condition following the March 4 nerve agent attack. Officials have not said what nerve agent was used or who is to blame. The 66-year-old Skripal worked for Russian military intelligence before he was recruited to spy for Britain. Summary: – The Russian ex-spy poisoned in England was exposed to a military-grade nerve agent of a type produced by Russia, says British Prime Minister Theresa May. May told lawmakers during an address in parliament on Monday it was "highly likely' Russia was responsible for poisoning Sergei Skripal, the former Russian military intelligence officer who was convicted of spying for Britain, reports the AP. May says Russia's ambassador to the UK has been summoned to explain how a Russian nerve agent turned up in Salisbury, the English city where Skripal and his adult daughter were sickened. The BBC indicates May suggests Russian culpability: for either being behind the poisoning or "losing control" of a dose of nerve agent. The British prime minister says if Moscow is proven to be behind the poisoning, her government will consider it an "unlawful use of force" by Russia. Hours earlier, President Vladimir Putin had been asked by a British reporter in southern Russia if Russia was behind the poisoning. His response: "You first get to the bottom of things over there, and after that we can discuss it." Skripal and his daughter remain in critical condition following the March 4 nerve agent attack in England. Authorities still haven't specified which nerve agent was used.
{ "task_name": "multi_news" }
Passage 1: DeLorenzo DeLorenzo or De Lorenzo or de Lorenzo is an Italian surname. It may refer to: Passage 2: Rosa Rosa or De Rosa may refer to: Passage 3: De León De León or de León or De Leon may refer to: Passage 4: De cabaret-prinses De cabaret- prinses is a 1925 Dutch silent film directed by Theo Frenkel. Passage 5: Delisle Delisle or De Lisle or de Lisle may refer to: Passage 6: Tour Colombia The Tour Colombia, called earlier Colombia Oro y Paz is a stage professional cycling race held annually in Colombia since 2018. It is part of UCI America Tour in category 2.1. Passage 7: Cabaret Woman Cabaret Woman( Spanish: Una mujer de cabaret) is a 1974 Spanish comedy film directed by Pedro Lazaga and starring Carmen Sevilla and José María Rodero. Passage 8: DE DE, de, or dE may refer to: Passage 9: Carnival Nights Carnival Nights( Spanish: Noches de cabaret) is a 1978 Mexican comedy drama film directed by Rafael Portillo and starring Jorge Rivero, Sasha Montenegro and Carmen Salinas. Passage 10: Colombia Magia Salvaje Colombia Magia Salvaje( translatable into English as Colombia Wild Magic) is a Colombian documentary film released in 2015, directed by Mike Slee and produced for Éxito Group, by the Ecoplanet Foundation and the British firm Off The Fence. The film is a sample of the biodiversity of Colombia, recorded in 85 different locations to achieve the portrait of 20 ecosystems. Question: Which film came out earlier, Colombia Magia Salvaje or De Cabaret-Prinses? Answer: De Cabaret-Prinses
{ "task_name": "2WikiMultihopQA" }
Document: Barnes listed 31 incidents in the last decade in which Knight was accused of acting violently or threatening to do so, beginning with a 2004 report of a woman who claimed that, on Knight's orders, she was punched in the face outside the Four Seasons Hotel in Los Angeles. She later refused to cooperate with police, citing a fear of retaliation by Knight. ||||| LOS ANGELES (AP) — Former rap music mogul Marion "Suge" Knight collapsed in a courtroom Friday shortly after a judge ordered him held on $25 million bail in a murder case. Los Angeles Sheriff's deputies rush to assist Marion "Suge" Knight, as he suddenly fainted during an appearance in court for a bail review hearing in his murder case in Los Angeles on Friday, March 20,... (Associated Press) Marion "Suge" Knight appears in court for a bail review hearing in his murder case in Los Angeles on Friday, March 20, 2015. At left is his attorney Matthew Fletcher. Prosecutors are asking a judge to... (Associated Press) Marion "Suge" Knight closes his eyes as he appears in court for a bail review hearing in his murder case in Los Angeles on Friday, March 20, 2015. Prosecutors are asking a judge to set bail in a murder... (Associated Press) Marion "Suge" Knight, right, appears in court for a bail review hearing in his murder case in Los Angeles on Friday, March 20, 2015. At left his attorney , Matthew Fletcher. A judge set his bail at $25... (Associated Press) Bailiffs cleared the courtroom, paramedics arrived with a stretcher a few minutes later and an ambulance was seen leaving the courthouse. Defense attorney Matthew Fletcher said Knight was unconscious when the lawyer left the courtroom and an update on his condition was not immediately available. Fletcher said his client, who is diabetic and has a blood clot, previously told him that he hadn't received any medication since Thursday. Knight hit his head on a chair when he fell after the bail hearing, Fletcher said. The 6-foot-4-inch tall Knight collapsed while deputies were bringing him back into the courtroom after Fletcher asked a judge to order that Knight be given his medication. The attorney said Knight was being kept in solitary confinement in jail without proper access to medication. "He's being treated worse than Charles Manson," Fletcher said. The collapse marked the fourth time that Knight has been taken by ambulance from a courthouse since he was charged with killing Terry Carter, 55, in early February. Los Angeles Superior Court Judge Ronald S. Coen set bail on Friday at $25 million for Knight, who is accused of running down and killing Carter with his truck. Coen made his decision after Deputy District Attorney Cynthia Barnes noted that Knight was on bail in a robbery case when he struck Carter and another man in a parking lot in Compton. "He escalated his behavior and committed murder," Barnes told the judge. Fletcher argued that Knight's bail should be set at $2 million, but Coen said the higher amount was warranted. The attorney said before the hearing that his client likely could not post bail if it was set at $25 million. Knight, the 49-year-old co-founder of Death Row Records, has pleaded not guilty to murder, attempted murder and hit-and-run charges. Barnes filed a motion Thursday accusing Knight of being part of a scheme that has extorted more than $10 million from up-and-coming and established rappers in recent years. Fletcher countered that prosecutors should file charges involving those extortion claims if they have enough evidence. Fletcher also said phone records and other evidence in the murder case would show that Knight was lured to the location where the men were hit by the truck. Knight was attacked when he arrived and hit the two men while trying to flee the scene, the lawyer said. Fletcher said Cle "Bone" Sloan acknowledged to sheriff's investigators that he attacked Knight. The attorney argued his client wasn't required to remain at the scene and endure the attack, and that Sloan should be charged. "If his name wasn't 'Suge' Knight, they wouldn't have filed this case," Fletcher said. Knight was a key player in the gangster rap scene that flourished in the 1990s, his label once listing Dr. Dre, Tupac Shakur and Snoop Dogg among its artists. Knight lost control of the company after it was forced into bankruptcy. ___ Anthony McCartney can be reached at http://twitter.com/mccartneyAP ||||| Suge Knight Collapses in Court Nailed with $25 MIL Bail Suge Knight -- Collapses in Court Nailed with $25 MILLION Bail 10:15 AM PT -- Suge collapsed after the hearing, an ambulance came and they are taking him to the hospital. Certainly better than a 20 X 8 cell. Suge Knight just got the worst news possible ... a judge sided with the prosecutor in his murder case and set bail at $25 MILLION ... but not before his lawyer compared Suge's plight to Lucious Lyon on "Empire." The judge feels Suge is a danger to be out and about given his extensive record and specifically, incidents involving guns, violence and witness intimidation. Attorney Matt Fletcher threw a Hail Mary, accusing the prosecutor of watching too much "Empire." Fletcher, said, "It's like she watches "Empire" and comes in and says, 'He was an unrepentant and shameless criminal. Prosecute him.'" As you know ... Lucious was arrested in the "Empire" finale for murdering Bunkie. And then Fletcher starts to hammer away at Cle Bone Sloan, one of the men Suge ran over, repeatedly referencing Bone's statement to cops that he f***** Suge up. Suge is in bad shape, claiming he's going crazy in jail because he's in solitary with no hot water, no blanket and only sporadic showers. Summary: – Suge Knight ended up in the hospital today after getting some bad news in court. The 49-year-old collapsed after the judge in his murder case set bail at $25 million, reports the AP. The rap mogul's attorney—who TMZ reports sought bail of $2 million and accused prosecutors of watching too much Empire—says Knight hit his head on a chair when he fell and knocked himself out. He was being evaluated at a jail hospital in Los Angeles, reports the LA Times. It wasn't clear whether Knight, co-founder of Death Row Records, would be able to post bail once he was medically cleared. He is accused of fatally running over a man with his truck.
{ "task_name": "multi_news" }
Passage 1: Maximus (comics) Maximus is a fictional supervillain appearing in American comic books published by Marvel Comics. The character has been depicted both as a member of and antagonist to the Inhumans. Created by writer Stan Lee and artist Jack Kirby, he first appeared in "Fantastic Four" #47 (February 1966). Passage 2: Alicia Masters Alicia Reiss Masters is a fictional character appearing in American comic books published by Marvel Comics. She is usually depicted as a supporting character to the superheroes the Fantastic Four and Silver Surfer. Created by Stan Lee and Jack Kirby, she first appeared in "The Fantastic Four" #8 (Nov 1962). Passage 3: Episodes 1 and 2 (Inhumans) "Behold... The Inhumans" and "Those Who Would Destroy Us" are the first and second episodes, and two-part series premiere, of the American television series "Inhumans", initially released together as an IMAX film marketed as Inhumans: The First Chapter. Based on the Marvel Comics race of the same name, the episodes revolve around Black Bolt and other members of the Inhuman Royal Family, and are set in the Marvel Cinematic Universe (MCU), sharing continuity with the films and other television series of the franchise. The episodes were written by Scott Buck and directed by Roel Reiné, with series regulars Anson Mount, Serinda Swan, Ken Leung, Eme Ikwuakor, Isabelle Cornish, Ellen Woglom, and Iwan Rheon starring. The episodes see the Inhuman Royal Family exiled to Hawaii after a coup by Maximus. Passage 4: The Fantastic Four (unreleased film) The Fantastic Four is an independent superhero film completed in 1994. Executive produced by low-budget specialist Roger Corman and Bernd Eichinger (who went on to produce a big-budget "Fantastic Four" film in 2005), the film was based on Marvel Comics' long-running comic book and featured the origin of the Fantastic Four and that superhero team's first battle with the evil Doctor Doom, combining the superteam's origin from "The Fantastic Four" #1 and Doom's origin from "Fantastic Four Annual" #2 with original elements. Despite a tentative scheduled 1994 release date, the film was ultimately never released officially, but illegal copies began circulating after a few years. Passage 5: Fantastic Four: Rise of the Silver Surfer Fantastic Four: Rise of the Silver Surfer (stylized as 4: Rise of the Silver Surfer) is a 2007 American-British-German superhero film, based on the Marvel Comics superhero team the Fantastic Four. A sequel to the 2005 film "Fantastic Four", the film is directed by Tim Story. Ioan Gruffudd as Reed Richards, Jessica Alba as Sue Storm, Chris Evans as Johnny Storm, and Michael Chiklis as Ben Grimm are the film series' recurring protagonists, while Julian McMahon and Kerry Washington reprise their roles from the first film as Victor Von Doom and Alicia Masters, respectively. Beau Garrett appears as Frankie Raye, along with Doug Jones as the Silver Surfer, with Laurence Fishburne voicing the Surfer. The plot follows the Fantastic Four as they confront the Silver Surfer and attempt to save Earth from Galactus. The film grossed $289 million. It was released on Blu-ray and DVD on October 2, 2007. Passage 6: Wings of Fire (book series) Wings of Fire is a high-fantasy novel series by Tui T. Sutherland. Series are five books long, and feature five different point-of-views. Two spinoff series, "Legends", focusing on adding world history and backstory to vital characters, and are novel length, and the ebook short-stories "Winglets", focused on adding backstory to secondary characters. The plot of the first five books revolve around five young dragonets prophesied by the NightWing tribe to end the war for the SandWing throne. The plot of the second 5 books revolve around another prophecy and the Jade Winglet, a group of students attending Jade Mountain Academy (a school founded by the original five dragonets), one of whom prophesied the collapse of Jade Mountain. The series is currently being converted to a graphic novel format, beginning with "The Dragonet Prophecy". Currently, a total of 20 books have been confirmed (three mainstream arcs, one unpublished, four "Winglets", the paper back collection of the first three "Winglets", and one "Legends", and the graphic novel of the first book). Passage 7: Diablo (Marvel Comics) Diablo (Esteban Corazón de Ablo) is a fictional supervillain appearing in American comic books published by Marvel Comics. Diablo is an enemy of the Fantastic Four. He is depicted as an evil alchemist. Created by writer Stan Lee and artist Jack Kirby, the character first appeared in "Fantastic Four" vol. 1 #30 (September 1964). Passage 8: Black Bolt Black Bolt (Blackagar Boltagon) is a fictional character appearing in American comic books published by Marvel Comics. Created by Stan Lee and Jack Kirby, the character first appears in "Fantastic Four" #45 (December 1965). Black Bolt is the ruler of the Inhumans, a reclusive race of genetically altered superhumans. Black Bolt's signature power is his voice, as his electron-harnessing ability is linked to the speech center of his brain. Speaking triggers a massive disturbance in the form of a highly destructive shockwave capable of leveling a city. Due to the extreme danger posed by this power, the character has undergone rigorous mental training to prevent himself from uttering a sound, even in his sleep, and he usually remains completely silent and speaks through sign language or via spokesperson. Passage 9: Fantastic Four vs. the X-Men Fantastic Four vs. the X-Men (also known as X-Men vs Fantastic Four) is a four-issue comic book limited series published by Marvel Comics in 1987. Written by longtime "Uncanny X-Men" writer Chris Claremont, pencilled by Jon Bogdanove, and inked by Terry Austin, the series revolves around the quest to find an effective medical treatment for Kitty Pryde. Along the way, the Fantastic Four and the X-Men come into conflict with each other, and what appears to be a sinister secret regarding the Fantastic Four's origin comes to light. Passage 10: Fantastic Four Adventures Fantastic Four Adventures is part of Marvel UK's 'Collector's Edition' line. It is being published by Panini Comics but reprints Marvel Comics from the United States. It began in 2005 around the release of the Fantastic Four film and follows the format established by the Collector's Edition Range. "Fantastic Four Adventures" is sold once every 28 days through newsagents, although a subscription offer is available. "Fantastic Four Adventures" retailed at £2.40 upon its release, but rising in printing costs have seen the price rise to £2.50 and then onto the current price of £2.95. It was announced at the end of 2011 that "Fantastic Four Adventures" would cease publication with its final issue in March 2012, only to be replaced by a new CE, "Incredible Hulks". Question: Which character, who first appeared in "Fantastic Four" #45, does Inhumans: The First Chapter revolve around? Answer: Black Bolt
{ "task_name": "hotpotqa" }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion License using System; using System.Diagnostics; namespace Irony.Parsing { /// <summary> /// Parser class represents combination of scanner and LALR parser (CoreParser) /// </summary> public class Parser { public readonly ParserData Data; public readonly LanguageData Language; public readonly NonTerminal Root; //public readonly CoreParser CoreParser; public readonly Scanner Scanner; /// <summary> /// Either language root or initial state for parsing snippets - like Ruby's expressions in strings : "result= #{x+y}" /// </summary> internal readonly ParserState InitialState; private readonly Grammar grammar; public Parser(Grammar grammar) : this(new LanguageData(grammar)) { } public Parser(LanguageData language) : this(language, null) { } public Parser(LanguageData language, NonTerminal root) { this.Language = language; this.Data = Language.ParserData; this.grammar = Language.Grammar; this.Context = new ParsingContext(this); this.Scanner = new Scanner(this); this.Root = root; if (Root == null) { this.Root = this.Language.Grammar.Root; this.InitialState = this.Language.ParserData.InitialState; } else { if (this.Root != this.Language.Grammar.Root && !this.Language.Grammar.SnippetRoots.Contains(this.Root)) throw new Exception(string.Format(Resources.ErrRootNotRegistered, root.Name)); this.InitialState = this.Language.ParserData.InitialStates[this.Root]; } } public ParsingContext Context { get; internal set; } public ParseTree Parse(string sourceText) { return Parse(sourceText, "Source"); } public ParseTree Parse(string sourceText, string fileName) { var loc = default(SourceLocation); this.Reset(); /*if (Context.Status == ParserStatus.AcceptedPartial) { var oldLoc = Context.Source.Location; loc = new SourceLocation(oldLoc.Position, oldLoc.Line + 1, 0); } else { } }*/ this.Context.Source = new SourceStream(sourceText, this.Language.Grammar.CaseSensitive, this.Context.TabWidth, loc); this.Context.CurrentParseTree = new ParseTree(sourceText, fileName); this.Context.Status = ParserStatus.Parsing; var sw = new Stopwatch(); sw.Start(); this.ParseAll(); // Set Parse status var parseTree = Context.CurrentParseTree; var hasErrors = parseTree.HasErrors(); if (hasErrors) parseTree.Status = ParseTreeStatus.Error; else if (Context.Status == ParserStatus.AcceptedPartial) parseTree.Status = ParseTreeStatus.Partial; else parseTree.Status = ParseTreeStatus.Parsed; // Build AST if no errors and AST flag is set bool createAst = this.grammar.LanguageFlags.IsSet(LanguageFlags.CreateAst); if (createAst && !hasErrors) this.Language.Grammar.BuildAst(this.Language, parseTree); // Done; record the time sw.Stop(); parseTree.ParseTimeMilliseconds = sw.ElapsedMilliseconds; if (parseTree.ParserMessages.Count > 0) parseTree.ParserMessages.Sort(LogMessageList.ByLocation); return parseTree; } public ParseTree ScanOnly(string sourceText, string fileName) { this.Context.CurrentParseTree = new ParseTree(sourceText, fileName); this.Context.Source = new SourceStream(sourceText, this.Language.Grammar.CaseSensitive, this.Context.TabWidth); while (true) { var token = this.Scanner.GetToken(); if (token == null || token.Terminal == this.Language.Grammar.Eof) break; } return this.Context.CurrentParseTree; } internal void Reset() { this.Context.Reset(); Scanner.Reset(); } private void ParseAll() { // Main loop this.Context.Status = ParserStatus.Parsing; while (this.Context.Status == ParserStatus.Parsing) { this.ExecuteNextAction(); } } #region Parser Action execution internal ParserAction GetNextAction() { var currState = this.Context.CurrentParserState; var currInput = this.Context.CurrentParserInput; if (currState.DefaultAction != null) return currState.DefaultAction; ParserAction action; // First try as keyterm/key symbol; for example if token text = "while", then first try it as a keyword "while"; // if this does not work, try as an identifier that happens to match a keyword but is in fact identifier Token inputToken = currInput.Token; if (inputToken != null && inputToken.KeyTerm != null) { var keyTerm = inputToken.KeyTerm; if (currState.Actions.TryGetValue(keyTerm, out action)) { #region comments // Ok, we found match as a key term (keyword or special symbol) // Backpatch the token's term. For example in most cases keywords would be recognized as Identifiers by Scanner. // Identifier would also check with SymbolTerms table and set AsSymbol field to SymbolTerminal if there exist // one for token content. So we first find action by Symbol if there is one; if we find action, then we // patch token's main terminal to AsSymbol value. This is important for recognizing keywords (for colorizing), // and for operator precedence algorithm to work when grammar uses operators like "AND", "OR", etc. //TODO: This might be not quite correct action, and we can run into trouble with some languages that have keywords that // are not reserved words. But proper implementation would require substantial addition to parser code: // when running into errors, we need to check the stack for places where we made this "interpret as Symbol" // decision, roll back the stack and try to reinterpret as identifier #endregion comments inputToken.SetTerminal(keyTerm); currInput.Term = keyTerm; currInput.Precedence = keyTerm.Precedence; currInput.Associativity = keyTerm.Associativity; return action; } } // Try to get by main Terminal, only if it is not the same as symbol if (currState.Actions.TryGetValue(currInput.Term, out action)) return action; // If input is EOF and NewLineBeforeEof flag is set, try using NewLine to find action if (currInput.Term == this.grammar.Eof && this.grammar.LanguageFlags.IsSet(LanguageFlags.NewLineBeforeEOF) && currState.Actions.TryGetValue(this.grammar.NewLine, out action)) { // There's no action for EOF but there's action for NewLine. Let's add newLine token as input, just in case // action code wants to check input - it should see NewLine. var newLineToken = new Token(this.grammar.NewLine, currInput.Token.Location, "\r\n", null); var newLineNode = new ParseTreeNode(newLineToken); this.Context.CurrentParserInput = newLineNode; return action; } return null; } private void ExecuteNextAction() { // Read input only if DefaultReduceAction is null - in this case the state does not contain ExpectedSet, // so parser cannot assist scanner when it needs to select terminal and therefore can fail if (this.Context.CurrentParserInput == null && this.Context.CurrentParserState.DefaultAction == null) this.ReadInput(); // Check scanner error if (this.Context.CurrentParserInput != null && this.Context.CurrentParserInput.IsError) { this.RecoverFromError(); return; } // Try getting action var action = this.GetNextAction(); if (action == null) { if (this.CheckPartialInputCompleted()) return; this.RecoverFromError(); return; } // We have action. Write trace and execute it if (this.Context.TracingEnabled) this.Context.AddTrace(action.ToString()); action.Execute(this.Context); } #endregion Parser Action execution #region reading input public void ReadInput() { Token token; Terminal term; // Get token from scanner while skipping all comment tokens (but accumulating them in comment block) do { token = Scanner.GetToken(); term = token.Terminal; if (term.Category == TokenCategory.Comment) this.Context.CurrentCommentTokens.Add(token); } while (term.Flags.IsSet(TermFlags.IsNonGrammar) && term != this.grammar.Eof); // Check brace token if (term.Flags.IsSet(TermFlags.IsBrace) && !CheckBraceToken(token)) token = new Token(this.grammar.SyntaxError, token.Location, token.Text, string.Format(Resources.ErrUnmatchedCloseBrace, token.Text)); // Create parser input node this.Context.CurrentParserInput = new ParseTreeNode(token); // Attach comments if any accumulated to content token if (token.Terminal.Category == TokenCategory.Content) { this.Context.CurrentParserInput.Comments = this.Context.CurrentCommentTokens; this.Context.CurrentCommentTokens = new TokenList(); } // Fire event on Terminal token.Terminal.OnParserInputPreview(this.Context); } #endregion reading input #region Error Recovery public void RecoverFromError() { this.Data.ErrorAction.Execute(this.Context); } #endregion Error Recovery #region Utilities /// <summary> /// We assume here that the token is a brace (opening or closing) /// </summary> /// <param name="token"></param> /// <returns></returns> private bool CheckBraceToken(Token token) { if (token.Terminal.Flags.IsSet(TermFlags.IsOpenBrace)) { this.Context.OpenBraces.Push(token); return true; } // It is closing brace; check if we have opening brace in the stack var braces = this.Context.OpenBraces; var match = (braces.Count > 0 && braces.Peek().Terminal.IsPairFor == token.Terminal); if (!match) return false; // Link both tokens, pop the stack and return true var openingBrace = braces.Pop(); openingBrace.OtherBrace = token; token.OtherBrace = openingBrace; return true; } private bool CheckPartialInputCompleted() { bool partialCompleted = (this.Context.Mode == ParseMode.CommandLine && this.Context.CurrentParserInput.Term == this.grammar.Eof); if (!partialCompleted) return false; this.Context.Status = ParserStatus.AcceptedPartial; // clean up EOF in input so we can continue parsing next line this.Context.CurrentParserInput = null; return true; } #endregion Utilities } }
{ "task_name": "lcc" }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Compatibility functionality for Windbg users. """ import argparse import codecs import math import sys from builtins import str import gdb import pwndbg.arch import pwndbg.commands import pwndbg.memory import pwndbg.strings import pwndbg.symbol import pwndbg.typeinfo def get_type(size): return { 1: pwndbg.typeinfo.uint8, 2: pwndbg.typeinfo.uint16, 4: pwndbg.typeinfo.uint32, 8: pwndbg.typeinfo.uint64, }[size] parser = argparse.ArgumentParser(description="Starting at the specified address, dump N bytes.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") parser.add_argument("count", type=pwndbg.commands.AddressExpr, default=64, nargs="?", help="The number of bytes to dump.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def db(address, count=64): """ Starting at the specified address, dump N bytes (default 64). """ return dX(1, address, count, repeat=db.repeat) parser = argparse.ArgumentParser(description="Starting at the specified address, dump N words.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") parser.add_argument("count", type=pwndbg.commands.AddressExpr, default=32, nargs="?", help="The number of words to dump.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def dw(address, count=32): """ Starting at the specified address, dump N words (default 32). """ return dX(2, address, count, repeat=dw.repeat) parser = argparse.ArgumentParser(description="Starting at the specified address, dump N dwords.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") parser.add_argument("count", type=pwndbg.commands.AddressExpr, default=16, nargs="?", help="The number of dwords to dump.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def dd(address, count=16): """ Starting at the specified address, dump N dwords (default 16). """ return dX(4, address, count, repeat=dd.repeat) parser = argparse.ArgumentParser(description="Starting at the specified address, dump N qwords.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") parser.add_argument("count", type=pwndbg.commands.AddressExpr, default=8, nargs="?", help="The number of qwords to dump.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def dq(address, count=8): """ Starting at the specified address, dump N qwords (default 8). """ return dX(8, address, count, repeat=dq.repeat) parser = argparse.ArgumentParser(description="Starting at the specified address, hexdump.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") parser.add_argument("count", type=pwndbg.commands.AddressExpr, default=8, nargs="?", help="The number of bytes to hexdump.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def dc(address, count=8): return pwndbg.commands.hexdump.hexdump(address=address, count=count) def dX(size, address, count, to_string=False, repeat=False): """ Traditionally, windbg will display 16 bytes of data per line. """ values = [] if repeat: count = dX.last_count address = dX.last_address else: address = int(address) & pwndbg.arch.ptrmask count = int(count) type = get_type(size) for i in range(count): try: gval = pwndbg.memory.poi(type, address + i * size) # print(str(gval)) values.append(int(gval)) except gdb.MemoryError: break if not values: print('Could not access the provided address') return n_rows = int(math.ceil(count * size / float(16))) row_sz = int(16 / size) rows = [values[i*row_sz:(i+1)*row_sz] for i in range(n_rows)] lines = [] # sys.stdout.write(repr(rows) + '\n') for i, row in enumerate(rows): if not row: continue line = [enhex(pwndbg.arch.ptrsize, address + (i*16)),' '] for value in row: line.append(enhex(size, value)) lines.append(' '.join(line)) if not to_string: print('\n'.join(lines)) dX.last_count = count dX.last_address = address + len(rows)*16 return lines def enhex(size, value): value = value & pwndbg.arch.ptrmask x = "%x" % abs(value) x = x.rjust(size * 2, '0') return x parser = argparse.ArgumentParser(description="Write hex bytes at the specified address.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, nargs="*", help="The bytes to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def eb(address, data): """ Write hex bytes at the specified address. """ return eX(1, address, data) parser = argparse.ArgumentParser(description="Write hex words at the specified address.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, nargs="*", help="The words to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def ew(address, data): """ Write hex words at the specified address. """ return eX(2, address, data) parser = argparse.ArgumentParser(description="Write hex dwords at the specified address.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, nargs="*", help="The dwords to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def ed(address, data): """ Write hex dwords at the specified address. """ return eX(4, address, data) parser = argparse.ArgumentParser(description="Write hex qwords at the specified address.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, nargs="*", help="The qwords to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def eq(address, data): """ Write hex qwords at the specified address. """ return eX(8, address, data) parser = argparse.ArgumentParser(description="Write a string at the specified address.") parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, help="The string to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def ez(address, data): """ Write a character at the specified address. """ return eX(1, address, data, hex=False) parser = argparse.ArgumentParser(description="Write a string at the specified address.") #TODO Is eza just ez? If so just alias. I had trouble finding windbg documentation defining ez parser.add_argument("address", type=pwndbg.commands.HexOrAddressExpr, help="The address to write to.") parser.add_argument("data", type=str, help="The string to write.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def eza(address, data): """ Write a string at the specified address. """ return ez(address, data) def eX(size, address, data, hex=True): """ This relies on windbg's default hex encoding being enforced """ if not data: print('Cannot write empty data into memory.') return if hex: # Early validation if all data is hex for string in data: if string.startswith('0x'): string = string[2:] if any(ch not in '0123456789abcdefABCDEF' for ch in string): print('Incorrect data format: it must all be a hex value (0x1234 or 1234, both interpreted as 0x1234)') return writes = 0 for i, string in enumerate(data): if hex: if string.startswith('0x'): string = string[2:] string = string.rjust(size*2, '0') data = codecs.decode(string, 'hex') else: data = string if pwndbg.arch.endian == 'little': data = data[::-1] try: pwndbg.memory.write(address + (i * size), data) writes += 1 except gdb.error: print('Cannot access memory at address %#x' % address) if writes > 0: print('(Made %d writes to memory; skipping further writes)' % writes) return parser = argparse.ArgumentParser(description="Dump pointers and symbols at the specified address.") parser.add_argument("addr", type=pwndbg.commands.HexOrAddressExpr, help="The address to dump from.") @pwndbg.commands.ArgparsedCommand(parser,aliases=['kd','dps','dqs']) #TODO are these really all the same? They had identical implementation... @pwndbg.commands.OnlyWhenRunning def dds(addr): """ Dump pointers and symbols at the specified address. """ return pwndbg.commands.telescope.telescope(addr) da_parser = argparse.ArgumentParser() da_parser.description = 'Dump a string at the specified address.' da_parser.add_argument('address', type=pwndbg.commands.HexOrAddressExpr, help='Address to dump') da_parser.add_argument('max', type=int, nargs='?', default=256, help='Maximum string length') @pwndbg.commands.ArgparsedCommand(da_parser) @pwndbg.commands.OnlyWhenRunning def da(address, max): print("%x" % address, repr(pwndbg.strings.get(address, max))) ds_parser = argparse.ArgumentParser() ds_parser.description = 'Dump a string at the specified address.' ds_parser.add_argument('address', type=pwndbg.commands.HexOrAddressExpr, help='Address to dump') ds_parser.add_argument('max', type=int, nargs='?', default=256, help='Maximum string length') @pwndbg.commands.ArgparsedCommand(ds_parser) @pwndbg.commands.OnlyWhenRunning def ds(address, max): # We do change the max length to the default if its too low # because the truncated display is not that ideal/not the same as GDB's yet # (ours: "truncated ...", GDBs: "truncated "...) if max < 256: print('Max str len of %d too low, changing to 256' % max) max = 256 string = pwndbg.strings.get(address, max, maxread=4096) if string: print("%x %r" % (address, string)) else: print("Data at address can't be dereferenced or is not a printable null-terminated string or is too short.") print("Perhaps try: db <address> <count> or hexdump <address>") @pwndbg.commands.ArgparsedCommand("List breakpoints.") def bl(): """ List breakpoints """ gdb.execute('info breakpoints') parser = argparse.ArgumentParser(description="Disable the breakpoint with the specified index.") parser.add_argument("which", nargs="?", type=str, default='*', help="Index of the breakpoint to disable.") @pwndbg.commands.ArgparsedCommand(parser) def bd(which = '*'): """ Disable the breakpoint with the specified index. """ if which == '*': gdb.execute('disable breakpoints') else: gdb.execute('disable breakpoints %s' % which) parser = argparse.ArgumentParser(description="Enable the breakpoint with the specified index.") parser.add_argument("which", nargs="?", type=str, default='*', help="Index of the breakpoint to enable.") @pwndbg.commands.ArgparsedCommand(parser) def be(which = '*'): """ Enable the breakpoint with the specified index. """ if which == '*': gdb.execute('enable breakpoints') else: gdb.execute('enable breakpoints %s' % which) parser = argparse.ArgumentParser(description="Clear the breakpoint with the specified index.") parser.add_argument("which", nargs="?", type=str, default='*', help="Index of the breakpoint to clear.") @pwndbg.commands.ArgparsedCommand(parser) def bc(which = '*'): """ Clear the breakpoint with the specified index. """ if which == '*': gdb.execute('delete breakpoints') else: gdb.execute('delete breakpoints %s' % which) parser = argparse.ArgumentParser(description="Set a breakpoint at the specified address.") parser.add_argument("where", type=int, help="The address to break at.") @pwndbg.commands.ArgparsedCommand(parser) def bp(where): """ Set a breakpoint at the specified address. """ result = pwndbg.commands.fix(where) if result is not None: gdb.execute('break *%#x' % int(result)) parser = argparse.ArgumentParser(description="Starting at the specified address, disassemble N instructions.") parser.add_argument("where", type=int, nargs="?", default=None, help="The address to disassemble at.") parser.add_argument("n", type=int, nargs="?", default=5, help="The number of instructions to disassemble.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def u(where=None, n=5, to_string=False): """ Starting at the specified address, disassemble N instructions (default 5). """ if where is None: where = pwndbg.regs.pc return pwndbg.commands.nearpc.nearpc(where, n, to_string) @pwndbg.commands.ArgparsedCommand("Print a backtrace (alias 'bt').") @pwndbg.commands.OnlyWhenRunning def k(): """ Print a backtrace (alias 'bt') """ gdb.execute('bt') parser = argparse.ArgumentParser(description="List the symbols nearest to the provided value.") parser.add_argument("value", type=int, nargs="?", default=None, help="The address you want the name of.") @pwndbg.commands.ArgparsedCommand(parser) @pwndbg.commands.OnlyWhenRunning def ln(value=None): """ List the symbols nearest to the provided value. """ if value is None: value = pwndbg.regs.pc value = int(value) x = pwndbg.symbol.get(value) if x: result = '(%#x) %s' % (value, x) print(result) # The three commands are aliases for `vmmap` and are set so in vmmap.py # lm # address # vprot @pwndbg.commands.ArgparsedCommand("Not be windows.") @pwndbg.commands.OnlyWhenRunning def peb(): print("This isn't Windows!") @pwndbg.commands.ArgparsedCommand("Windbg compatibility alias for 'continue' command.") @pwndbg.commands.OnlyWhenRunning def go(): ''' Windbg compatibility alias for 'continue' command. ''' gdb.execute('continue') @pwndbg.commands.ArgparsedCommand("Windbg compatibility alias for 'nextcall' command.") @pwndbg.commands.OnlyWhenRunning def pc(): ''' Windbg compatibility alias for 'nextcall' command. ''' return pwndbg.commands.next.nextcall()
{ "task_name": "lcc" }
Document: Prior to CMIA, the timing of federal funds transfers to states was governed by the Intergovernmental Cooperation Act, Public Law 90-577. That law allowed a state to retain for its own purposes any interest earned on federal funds transferred to it “pending its disbursement for program purposes.” The House Committee on Government Operations, when considering the CMIA legislation in 1990, noted that the Intergovernmental Cooperation Act had been “the source of continuing friction between the states and the Federal Government.” The House Committee stated that under the Intergovernmental Cooperation Act, “the States need not account to the Federal Government for interest earned on Federal funds disbursed to the states prior to payment of program beneficiaries.” Several years earlier, in 1988, when the Senate Committee on Governmental Affairs had looked into this matter, it found that as a result, “some administering departments at the state level were drawing down Federal funds too far in advance of need, costing the Federal Government foregone interest.” Both committees pointed out, however, that whenever the federal government complained that states profited unduly from early drawdowns, states would recite “numerous instances where they lose interest opportunities because the Federal Government is slow to reimburse them for moneys the states advance to fund Federal programs.” At the request of the Senate Committee, a Joint State/Federal Cash Management Reform Task Force, comprised of financial management representatives from six states and six federal agencies, including OMB and Treasury, was formed in 1983 to seek fair and equitable solutions to the aforementioned problems relating to the transfer of funds between the federal government and the states. Its work contributed to passage of CMIA in October 1990. The House Committee expected that CMIA would “provide a fair and equitable resolution to those differences.” It would do so, according to the committee, by establishing “equitable cash transfer procedures, procedures whereby neither the Federal nor state governments profit or suffer financially due to such transfers.” CMIA, as enacted in 1990, requires the federal government to schedule transfers of funds to states “so as to minimize the time elapsing between transfer of funds from the United States Treasury and the issuance or redemption of checks, warrants, or payments by other means by a state,” and expects states to “minimize the time elapsing between transfer of funds from the United States Treasury and the issuance or redemption of checks, warrants, or payments by other means for program purposes.” To accomplish this goal, CMIA directed the Secretary of the Treasury to negotiate agreements with the individual states to specify procedures for carrying out transfers of funds with that state. It authorized the Secretary to issue regulations establishing such procedures for states with which the Secretary has been unable to reach agreement. The Senate Governmental Affairs Committee explained when considering a 1992 amendment to CMIA that the act is “meant to provide a self-enforcing incentive for both state and Federal agencies to time the transfer of Federal funds as closely as possible to their actual disbursement for program purposes, so that neither... will lose the time value of their funds.” The “self-enforcing incentive” that the Senate Committee refers to is the act’s interest liability provision. States are required to pay interest to the United States on federal funds transferred to the state from the time those funds are deposited to the state’s account until the time the state uses the funds to redeem checks or warrants or make payments by other means for program purposes. If a state advances its own funds for program purposes prior to a transfer of federal funds, the state is entitled to interest from the United States from the time the state’s own funds are paid out to redeem checks or warrants, or make payments by other means, until the federal funds are deposited to the state’s bank account. CMIA requires each state to calculate any interest liabilities of the state and federal government and calls for an annual exchange of the net interest owed by either party. Other key requirements of the act and/or Treasuryrules and regulations are as follows: The Department of the Treasury must establish rules and regulations for implementing CMIA. States and FMS may enter into Treasury-State Agreements (TSAs) that outline, by program, the funding technique and the clearance patternstates will use to draw down funds from the federal government. If any state and FMS do not enter into such an agreement, FMS will designate the funding technique and the interest calculation method to be used by that state. States may claim reimbursement from Treasury annually for allowable direct costs relating to development and maintenance of clearance patterns and the calculation of interest. States must prepare and submit to FMS an annual report that summarizes by program the results of the interest calculation from drawdowns and may include any claims for reimbursement of allowable direct costs. The federal program agencies are required to (1) schedule transfers of funds to the states so as to minimize the time elapsing between the disbursement of federal funds from the U.S. Treasury and the issuance and redemption of checks, warrants, or payments by other means by a state and (2) upon Treasury’s request, review annual reports submitted by the states for reasonableness and accuracy. During fiscal year 1994 (which, for the majority of states, included 9 months of the states’ first fiscal year under CMIA), the federal government obligated over a reported $150 billion in federal funds to the states for programs covered under the act. (See table 1.) These programs were funded by the Departments of Health and Human Services (HHS), Labor, Education, Agriculture, Transportation and the Social Security Administration. We did not independently verify the amounts in table 1. Our objective was to report, as required under the act, on CMIA’s implementation. Specifically, we determined whether as required under the act, the Department of the Treasury developed rules and regulations for implementing the act; the Treasury-State Agreements (TSAs) were negotiated in accordance with CMIA provisions and Treasury rules and regulations; the states we visited followed the funding techniques and clearance patterns approved by FMS in requesting and transferring funds; for the states we visited, interest was assessed to the federal government and states, in accordance with CMIA and Treasury rules and regulations; claims submitted by the states we visited for reimbursement of allowable direct costs incurred in implementing CMIA were prepared in accordance with Treasury regulations; the states submitted all required annual reports to FMS; and the federal program agencies (1) scheduled transfers of funds to the states so as to minimize the time elapsing between the disbursement of federal funds from the U.S. Treasury and the issuance and redemption of checks, warrants, or payments by other means by a state and (2) upon Treasury’s request, reviewed annual reports submitted by the states for reasonableness and accuracy. To accomplish these objectives, we (1) performed walkthroughs of how funds flow from the federal government to the states and how the states distribute the funds for program purposes, (2) interviewed state officials, (3) tested transactions, (4) interviewed state auditors, and (5) reviewed Single Audit Act reports. The Single Audit Act of 1984 requires each state or local government that receives $100,000 or more in federal financial assistance in any given year to have an annual comprehensive single audit of its financial operations, including tests to determine whether the entity complied with laws and regulations that may have a material effect on its financial statements or its major programs, as defined in the Single Audit Act. The Office of Management and Budget (OMB) publishes guidance to assist auditors in planning audits under the Single Audit Act of 1984. We also reviewed Treasury’s regulations, implementation plans, and procedures for reviewing TSAs and annual reports. In addition, we sent a questionnaire to all states to obtain their views on CMIA implementation and summarized the results of the 54 completed and returned questionnaires. To determine if the federal program agencies and the states were properly implementing CMIA, we also documented systems used to process selected transactions of eight major programs (National School Lunch, Unemployment Insurance, Chapter 1-Local Education, Family Support Payments to States, Social Services Block Grant, Medical Assistance, Highway Planning and Construction, and Supplemental Security Income). These programs were selected on the basis of federal funding levels and the amount of interest liabilities incurred during the first year of CMIA implementation. It was not part of our scope to assess the adequacy of the accounting systems states and federal program agencies used to carry out their CMIA requirements. The period covered by the audit was the states’ 1994 fiscal year, which, for almost all of the states, was the period from July 1, 1993 through June 30, 1994. The first required annual reports were due by December 31, 1994, and the first interest exchange between the states and the federal government occurred on or about March 1, 1995. The 12 states selected for detailed audit work were chosen primarily because they received relatively large amounts of federal funds, incurred comparatively large federal or state interest liabilities, and, in some cases, were denied interest and direct costs reimbursement claims submitted to FMS. We included states that reported interest liabilities to or from the federal government (California, Colorado, Florida, Indiana, Maryland, New York, Ohio, Pennsylvania, Texas, and Tennessee) and states that reported no state or federal interest liabilities (District of Columbia and Georgia). We also visited the Departments of Health and Human Services, Labor, Education, Agriculture, Transportation and the Social Security Administration because they process requests for funds for the programs we selected for audit and review federal interest liabilities relating to these programs. We conducted our audit between April and September 1995 at 12 states, 6 federal program agencies, and FMS. We performed our work in accordance with generally accepted government auditing standards. While we performed limited testing of the reasonableness of the calculated interest liability and reimbursement of the direct costs for the 12 states visited, our audit scope did not include an assessment of the accuracy and completeness of the $34 million net interest liability (comprised of $41.6 million of state interest liabilities offset by a $4.7 federal interest liability and $2.5 million in states’ claims for direct costs reimbursement), nor did we test the accuracy of program disbursements made by the states. We provided a draft of this report to Treasury’s FMS for review and comment. FMS agreed with our findings and conclusions. Our review showed that the Department of the Treasury, federal program agencies, and the states have made substantial progress in achieving the act’s purpose of timely transfers of funds. Most state officials acknowledged that CMIA has helped heighten their awareness of cash management, but several expressed concern over what they viewed as added administrative burden. While the three key agents have made progress in implementing CMIA, three of the states we visited consistently did not comply with certain Treasury rules and regulations. Some of the noncompliance situations resulted in an understatement in the states’ reported state interest liability. However, because it was outside the scope of our audit, we did not attempt to project the total understatements resulting from these noncompliances. We communicated these noncompliances to FMS, and it informed us that it will take appropriate actions to address the noncompliances. As amended, CMIA directed that by July 1, 1993, or the first day of a state’s fiscal year beginning in 1993, whichever is later, the Secretary of the Treasury was to make all reasonable efforts to enter into a written agreement with each state that receives a transfer of federal funds. This agreement was to document the procedures and requirements for the transfer of funds between federal executive branch agencies and the states. In addition, the Secretary was to issue rules and regulations within 3 years relating to the implementation of CMIA. FMS officials have made substantial efforts to enable successful implementation. They published final rules and regulations for implementing CMIA; contracted for development of clearance patterns that could be used by states that did not develop their own; developed and issued an Implementation Guide, Federal and State Review Guides, and a Treasury-State Agreement Form Book; negotiated first year TSAs, within the time period specified in the act, with all but two states and second year agreements with all but one state; reviewed the documentation for reimbursement of allowable direct costs over $50,000 submitted by the states; received first-year annual reports from all the states and submitted them to program agencies for review of federal interest liabilities claimed; issued several policy statements intended to clarify regulations; submitted to OMB suggested language on CMIA-related audit objectives and procedures for inclusion in the planned revisions to the Compliance Supplement for Single Audit Act reviews; and developed plans to revise the CMIA regulations to streamline processes to make them more flexible. As part of its revision of the CMIA regulations, FMS plans to allow for greater variation in funding techniques and to delete descriptions and examples of the four current funding techniques from the regulations. Thus, according to FMS, states will be able to choose a technique that meets their needs. FMS also plans to eliminate the prohibition on reimbursable funding to provide states with greater flexibility in funding techniques. In the same regard, we found that the federal program agencies met their responsibilities under the act to transfer funds in a timely manner. This is evidenced by the relatively small (approximately $4.7 million) federal interest liability incurred in the first year of the act’s implementation. State officials generally credit CMIA with heightening their awareness of cash management matters. Even though several of them said that they had been practicing cash management techniques prior to CMIA, they still believed that CMIA was instrumental in focusing attention on when federal funds should be requested. Of the 54 states responding to our questionnaire, 41 stated that CMIA raised their level of awareness regarding cash management. Thirty-two said that CMIA is needed to ensure financial equity in the transfer of funds. The 12 states we visited were generally making a good effort to comply with CMIA requirements. The following sections describe actions states have taken and provide additional details on actions taken by the 12 states we visited and the noncompliance situations we found at 3 of the states. Treasury-State Agreement: All but 2 of the 56 states and all of the 12 states visited signed a first year TSA with FMS. Clearance Pattern Methodology: Nine of the states we visited developed their own clearance patterns based on techniques described in the Treasury regulations. Three chose to accept a clearance pattern time provided by FMS based on a study done under contract for the federal government. In an effort to be efficient, a few states are testing clearance patterns on a quarterly basis, even though they are not required by Treasury regulations to recertify their clearance patterns more frequently than every 5 years. Adherence to Agreed to Drawdown Techniques: For all the programs included in our review, we tested to determine whether states we visited were drawing down federal funds in accordance with the terms contained in their agreements. Generally, we noted that drawdowns complied with agreement terms. However, in one state, the agreed upon drawdown techniques were consistently not followed for six of the seven programs tested. For example, two programs were consistently drawing funds several days prior to the TSA specified schedule. According to program officials, the agreed upon funding techniques negotiated by the state treasurer’s office did not reflect the actual timing of when these funds were clearing accounts. Therefore, the program officials drew the funds in what they thought was a more accurate manner. In addition, the state filed an amended annual report with FMS reducing its net state liability from about $500,000 to $60,000. The state informed FMS that it had followed its agreed upon funding techniques in all its programs and, therefore, was reducing its previously reported interest liability. However, as mentioned above, we found that the state was consistently not following its agreed upon funding techniques. In another state, our work showed that no attempt was made to draw down in accordance with the funding technique for 5 of the programs tested. According to program officials, they were unaware of the techniques specified in the agreement because they were not consulted before the agreement was approved nor had they seen the agreement after it went into effect. In this case, no federal interest liability was created since funds were being transferred to the states in a timely manner whenever they were requested. However, in the transactions we looked at, this did result in the state consistently using its own money to fund programs until it received federal funds. Interest Calculation: Ten of the 12 states we visited computed interest liabilities. Both states that did not make such computations told us they had no interest liabilities to compute. However, our review showed that one of these states should have computed an interest liability on certain refunds it received. Our tests of interest calculations showed some problems. For example, one state claimed a federal interest liability because it did not receive federal funds by the time specified in the TSA. FMS denied a significant portion of this claim because it concluded that the state was not requesting funds in time for the federal government to provide them as called for in the agreement. We attempted to determine the reasonableness of the state’s claim, but state officials told us that they no longer had sufficient documentation to support their claim. Direct Cost: The Treasury regulations authorize states to claim reimbursement for direct costs incurred for developing and maintaining clearance patterns and computing interest liabilities. Reimbursable direct costs were claimed by 11 of the 12 states we visited. FMS denied a significant portion of the direct cost claims for two of these states. FMS denied a portion of the claims because the documentation submitted did not support costs allowable under CMIA. One state has appealed the decision and the other is considering an appeal. In those cases where reimbursement was approved, our review of supporting documentation indicated that the states had reasonable support for their claims. Annual Reports: All 56 states submitted an annual report to FMS for the first year’s activities. While overall states see benefits from CMIA, such as a heightened awareness of cash management, some expressed concern about what they perceived as an additional burden of the act. In 24 of the 54 responses to our questionnaire and 7 of the 12 states we visited, officials expressed their view that the additional administrative tasks associated with implementing the act are burdensome. In addition, officials at 2 of the states we visited stated that the CMIA regulations were inflexible. Some of the issues cited by the states included: Administrative tasks needed to comply with CMIA, such as preparing TSAs and annual reports, developing clearance patterns, computing interest liabilities, tracking refunds, and compiling direct costs, are burdensome to their operations. Three states said that the Treasury was being inflexible by not allowing them to use the reimbursable funding technique, which is a method of transferring federal funds to a state after the state has paid out its own funds for program purposes. After June 30, 1994, Treasury regulations prohibited reimbursable funding, except where mandated by federal law. One state said that it believed that the act itself does not specifically prohibit reimbursable funding and that some federal assistance programs must use it as a necessity. It said that using another funding technique that requires estimating cash needs in advance and reconciling later to actual expenditures creates an unnecessary administrative burden. It also said that the cash needs for some programs cannot be estimated due to fluctuating activities. As we discussed earlier, FMS is planning to revise the CMIA regulations to allow for the use of reimbursable funding. A Treasury policy statement requires that average clearance patterns be calculated out until 99 percent of the funds have cleared through the bank account. Some of the states said that this degree of precision was unnecessary because it requires them to make excessive small dollar amount draws. Treasury regulations require states to compute interest on refunds for which the federal share is $10,000 or more. Several of the states said that monitoring all programs covered by CMIA for refunds was burdensome given that most of these refunds relate to one federal program. We determined that over 90 percent of all state interest liabilities from refunds reported by the states in the first year annual reports related to one federal program. Some states said that the Treasury regulatons should allow reimbursement for all direct costs related to implementing CMIA and not just those costs related to the three specific categories identified in the regulations. We did not determine the extent of burden created by the added administrative tasks placed on the states as a result of implementing CMIA. However, it should be noted that the states can submit claims for reimbursement for some of the efforts required. Also, some of the tasks, such as preparing TSAs and annual reports, developing clearance patterns, and computing interest liabilities should be less onerous now that the initial processes for generating this information have been established. Under CMIA, a state is authorized to draw down funds based on approved funding techniques. If the state requests funds early, interest is due the federal government. Conversely, if the federal government fails to transfer funds on time, the state is due interest. Ideally, under the act, the transfer of funds would be interest neutral, with neither the federal government nor the states incurring any interest liability. The first year of implementation of CMIA resulted in a cumulative net state interest liability due to the federal government of approximately $34 million. Taken in context, this liability is relatively small compared to the over $150 billion reported as obligated in fiscal year 1994 for the programs covered by the act. Table 2 summarizes the components of the $34 million net state interest liability. Interest claims are submitted by program. FMS denied 47 claims by 15 states for interest (approximately $6.4 million). Reasons cited included insufficient documentation and repeated failure to follow the funding technique specified in the TSA. As of October 1995, 8 of the 15 states had appealed those denials to FMS. Of the 8 states that filed claims to appeal these denials, all but 2 have been resolved. FMS denied a portion of direct cost reimbursement claims submitted by 10 states because the costs were not eligible for reimbursement under Treasury rules and regulations, or the supporting documentation contained both eligible and ineligible costs which could not be separately identified. Three states submitted claims to appeal the denials; two of these states’ appeals were subsequently approved based on additional supporting documentation provided to FMS. As indicated previously, most of the states visited computed interest liabilities in accordance with TSAs, and the majority of the programs reviewed had interest neutral funding techniques, whereby neither the federal government nor the states incur interest. Much of the state interest liability was beyond state agencies’ immediate control and was instead attributed to certain states’ laws which require that they have the federal funds in the bank before they make any associated disbursements, as opposed to when the check clears the bank. Four of the 12 states we visited had a state interest liability totaling $18.5 million which primarily resulted from the states’ adherence to such laws. OMB publishes guidance to assist auditors in planning audits under the Single Audit Act of 1984. The guidance, entitled, Compliance Supplement for Single Audits of States and Local Governments, was last updated in September 1990 and does not address CMIA, which was enacted in October 1990. OMB plans to issue a revised Compliance Supplement during fiscal year 1996 which will address CMIA requirements. We reviewed and generally supported a draft of the proposed revisions to the Compliance Supplement relating to cash management. However, we suggested that the Compliance Supplement also include provisions to determine that clearance patterns were properly established and verified by the appropriate state official. The fiscal year 1994 single audit reports for the states we visited lacked consistency and comprehensiveness in checking for compliance with CMIA requirements. Auditors in some of the states we visited said that they obtained knowledge about CMIA by obtaining FMS’ guidelines to state governments and attended cash management and audit conferences where CMIA was discussed. The auditors also said that they intended to expand work in their next audits to cover other aspects of CMIA requirements such as clearance pattern establishment and compliance with drawdown techniques contained in the TSA. FMS officials informed us that they do not routinely receive a copy of single audit reports from each state. Under the single audit concept, audited entities are only required to submit single audit reports to federal agencies that directly provide them funds and the Single Audit Clearinghouse, Governments Division, of the Commerce Department. Since FMS is not a funding agency, entities would not be required to submit reports to FMS. However, FMS may obtain copies of single audit reports from the Federal Audit Clearinghouse. Since some states comply with Single Audit Act requirements by arranging for single audit reports for each state department and agency that receives federal assistance, rather than one single audit for the entire state, FMS would in those cases need to obtain multiple reports for a given state. FMS officials also informed us that they do not routinely review the reports they do receive for CMIA findings. In our June 1994 report on the single audit process, we pointed out that single audit reports are not user friendly. We recommended that the auditors include a summary of their determinations concerning the entity’s financial statements, internal controls, and compliance with laws and regulations. The summary information would be useful because single audit reports generally contain seven or more reports from the auditor. We also recommended that the results of all single audits be made more accessible by having the Federal Audit Clearinghouse compile the results in an automated database. We believe that more useful information on compliance with cash management requirements, particularly when summarized in an accessible database, would provide FMS officials with a better basis for reviewing and acting on CMIA issues. The Cash Management Improvement Act has heightened awareness of cash management at both the state and federal levels. Treasury, the federal agencies, and the states have made substantial progress in implementing the act. By implementing its plans to begin revising CMIA regulations to streamline the process and placing greater emphasis on using the results of single audits as a means of overseeing state activities and enforcing CMIA requirements, FMS should be able to further improve the act’s effectiveness and help alleviate any concerns about administrative burden. We are also sending this report to the Secretary of the Treasury; the Commissioner of the Financial Management Service, Department of the Treasury; the Director of the Office of Management and Budget; and the Chairmen and Ranking Minority Members of the House Committee on Government Reform and Oversight, Subcommittee on Government Management, Information and Technology and Senate Committee on Governmental Affairs. We will also send copies to others on request. This report was prepared under the direction of Gregory M. Holloway, Director, Governmentwide Audits, who may be reached at (202) 512-9510 if you or your staffs have any questions. Other major contributors to this report were Gary T. Engel, Senior Assistant Director; J. Lawrence Malenich, Assistant Director; and Johnny R. Bowen, Senior Audit Manager. Gene L. Dodaro Assistant Comptroller General The first copy of each GAO report and testimony is free. Additional copies are $2 each. Orders should be sent to the following address, accompanied by a check or money order made out to the Superintendent of Documents, when necessary. Orders for 100 or more copies to be mailed to a single address are discounted 25 percent. U.S. General Accounting Office P.O. Box 6015 Gaithersburg, MD 20884-6015 Room 1100 700 4th St. NW (corner of 4th and G Sts. NW) U.S. General Accounting Office Washington, DC Orders may also be placed by calling (202) 512-6000 or by using fax number (301) 258-4066, or TDD (301) 413-0006. Each day, GAO issues a list of newly available reports and testimony. To receive facsimile copies of the daily list or any list from the past 30 days, please call (202) 512-6000 using a touchtone phone. A recorded menu will provide information on how to obtain these lists. Summary: Pursuant to a legislative requirement, GAO reviewed the Financial Management Service's (FMS), federal agencies', and states' implementation of the Cash Management Improvement Act (CMIA) during 1994. GAO found that: (1) FMS, federal agencies, and states have complied with CMIA requirements, established processes to implement CMIA, and made progress in achieving the act's goal of timely fund transfers; (2) total state interest liability during the first year of CMIA implementation was about $34 million; (3) states reported that while CMIA has improved their awareness of cash management, they are burdened by added administrative tasks; (4) states have not been able to effectively measure their compliance with CMIA, since the Office of Management and Budget has not published guidance for testing CMIA compliance; (5) FMS is taking action to address instances of state noncompliance in implementing CMIA which resulted in understatements of reported state interest liability; and (6) FMS is planning to revise CMIA regulations to allow states greater flexibility in funding techniques.
{ "task_name": "govreport_summarization" }
Document: FILE - This May 13, 2013 file photo shows O.J. Simpson during an evidentiary hearing in Clark County District Court in Las Vegas. Simpson's lawyers submitted a supersized appeal May 21, 2014, asking the... (Associated Press) FILE - This May 13, 2013 file photo shows O.J. Simpson during an evidentiary hearing in Clark County District Court in Las Vegas. Simpson's lawyers submitted a supersized appeal May 21, 2014, asking the... (Associated Press) LAS VEGAS (AP) — O.J. Simpson's lawyers submitted a supersized appeal to the Nevada Supreme Court, seeking the former football star's release from prison and a new trial in his 2007 Las Vegas armed-robbery case. The lawyers met a midnight Wednesday deadline to submit a request for the court to review Simpson's claim that 2008 trial in Las Vegas was tainted by his fame and notoriety following his 1995 acquittal in Los Angeles in the deaths of his ex-wife and her friend. However, the document totaled 19,993 words, court spokesman Michael Sommermeyer said Thursday. That was some 43 percent longer than the 14,000-word limit the court had set. It will be up to the seven justices to decide whether to accept it for filing and consideration. Until that time, the document hasn't been made public. The court hasn't decided whether to hear oral arguments. Simpson, 66, is serving nine to 33 years in a northern Nevada prison after being found guilty of leading a group of armed men in a September 2007 confrontation with two sports memorabilia dealers at a Las Vegas casino hotel. He was convicted of kidnapping, armed robbery and other charges. He's not eligible for parole until late 2017. The appeal stems from arguments rejected last year by Clark County District Judge Linda Marie Bell that Simpson's trial attorney botched Simpson's trial and first appeal to the state Supreme Court, the only appeals court in Nevada. Simpson attorney Patricia Palm said the appeal ran long because she and attorneys Ozzie Fumo and Tom Pitaro were responding in detail to the judge's Nov. 26 ruling, which totaled 101 pages. Palm said the state high court routinely accepts oversized filings in complex cases. She also submitted 36 appendices to the appeal brief. Bell's ruling came after she held five days of hearings in Las Vegas on a 94-page petition that Palm filed in May 2012 seeking a new trial on 22 possible grounds. The judge said she reviewed the entire Simpson court record and determined that evidence was overwhelming that Simpson orchestrated the armed kidnapping and robbery, and that Simpson's current attorneys failed to demonstrate how his former lawyer's actions changed the outcome of the case. Clark County District Attorney Steve Wolfson said he was confident that Bell's ruling would be upheld. Wolfson's wife, former Clark County District Judge Jackie Glass, presided over Simpson's 2008 trial and sentencing. Simpson claimed he was trying to retrieve from the memorabilia dealers items that had been stolen from him after his Los Angeles trial and a 1997 civil court a wrongful-death judgment that put him on the hook for $33.5 million to the estates of his ex-wife, Nicole Brown Simpson, and her friend, Ron Goldman. The NFL hall of famer testified last year that he thought he had a right to get his own belongings back, and he never knew any of the men with him were carrying guns. ___ Find Ken Ritter on Twitter: http://twitter.com/krttr ||||| O.J. Simpson is asking the Nevada Supreme Court to reverse a judge’s ruling denying him a new trial in a 2007 robbery case, in an appeal filed in the wee hours Thursday. Simpson is in the midst of serving a nine- to 33-year prison term after he was convicted of 10 charges for robbing two men of sports memorabilia in September 2007. He argued he was simply recovering his own property, including photographs, when he went to the Palace Station hotel room. The appeal motion, written by defense lawyer Patricia Palm, is longer than the Supreme Court allows by about 5,000 words. The high court must approve the longer version, which it has done in the past in other cases. Normally appeals are immediately posted on the Supreme Court’s website for public review, but Simpson’s had not posted Thursday because of the length. The appeal has more than 30 appendices to it, the Supreme Court’s website shows. In November, Judge Linda Bell rejected the notorious former football player’s contention that his trial lawyer in the robbery case, Yale Galanter, was ineffective, had financial and legal conflicts and misadvised the 66-year-old inmate. Bell’s ruling came six months after a week-long hearing where Simpson testified Galanter told him he could legally take his property back and would represent him for free. “All grounds in the petition lack merit and, consequently are denied,” Bell said in a 100-page decision. Bell ruled Simpson “failed to demonstrate that counsel experienced an actual conflict of interest that substantially impacted counsel’s performance at trial … that the State withheld exculpatory evidence … that appellate and trial counsel were ineffective or that any deficient performance by counsel resulted in prejudice,” the ruling stated. In her ruling, Bell said the evidence was overwhelming against Simpson and that there was no indication that it was a close verdict. Meanwhile, Simpson is in the midst of serving one to six years on a weapons enhancement for the kidnapping count. He has four to 18 years left on his prison term on the remaining counts. Simpson is imprisoned at Lovelock Correctional Center, about 100 miles northeast of Reno. Inmate #1027820 has had a “positive record,” the Nevada Board of Parole Commissioners said in July, which included his participation in parole programs. Following his Hall of Fame professional football career, Simpson became one of the most popular former athletes in America, regularly hawking products in humorous TV commercials or starring in movies, such as “The Naked Gun.” That is, until Simpson was acquitted by a Los Angeles jury in 1995 of the 1994 deaths of his wife, Nicole Brown Simpson, and Ronald Goldman in what was dubbed “the trial of the century.” Testimony at the May hearing revealed that most of the items taken in the 2007 robbery were found to be the football player’s. The items were returned to Simpson and, unless sold, were not subject to satisfy a $33.5 million civil judgment against him for the deaths of his ex-wife and Goldman. Contact reporter Francis McCabe at [email protected] or 702-380-1039. Find him on Twitter: @fjmccabe Summary: – OJ Simpson is seeking a new trial, arguing that the notoriety from his 1995 murder acquittal tainted his 2008 trial for a robbery in Las Vegas. His lawyers have filed an appeal with the Nevada Supreme Court, but it runs a mammoth 19,993 words and has more than 30 appendices; the AP points out that's 43% longer than the court's established word limit. It's not clear whether it will be accepted, though the Las Vegas Review-Journal reports the court has made such exceptions in the past. Simpson is serving nine to 33 years at the Lovelock Correctional Center in northern Nevada for his part in the armed robbery of two sports memorabilia dealers, but he argues that he was simply recovering his own property. He will not be eligible for parole until late 2017. The state's board of parole commissioners says Inmate #1027820 has had a "positive record," reports the Review-Journal. (He was, however, told off for stealing cookies last fall.)
{ "task_name": "multi_news" }
Passage 1: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 2: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 3: Jason Moore (director) Jason Moore( born October 22, 1970) is an American director of film, theatre and television. Passage 4: Brian Kennedy (gallery director) Brian Patrick Kennedy( born 5 November 1961) is an Irish- born art museum director who has worked in Ireland and Australia, and now lives and works in the United States. He is currently the director of the Peabody Essex Museum. He was the director of the Toledo Museum of Art in Ohio from 2010 to 2019. He was the director of the Hood Museum of Art from 2005 to 2010, and the National Gallery of Australia( Canberra) from 1997- 2004. Passage 5: Forbidden Island Forbidden Island is a 1959 American ColumbiaColor adventure crime film directed by Charles B. Griffith starring Jon Hall. It was his debut as director, although he had directed second unit on "Attack of the Crab Monsters". A young Don Preston from the Mothers of Invention appeared in this film. Passage 6: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Passage 7: Charles B. Griffith Charles Byron Griffith (September 23, 1930 – September 28, 2007) was a Chicago-born screenwriter, actor and film director, son of Donna Dameral, radio star of "Myrt and Marge", along with Charles' grandmother, Myrtle Vail, and was best known for writing Roger Corman productions such as "A Bucket of Blood" (1959), "The Little Shop of Horrors" (1960), and "Death Race 2000" (1975). He was credited with 29 movies, but is known to have written many more. He had also directed at least six films, acted in six films, was second unit director in six films, produced three films and was production manager of two films. During the late fifties and early sixties, Griffith created both redneck classics such as "Eat My Dust" and black comedies such as "A Bucket of Blood" and "The Little Shop of Horrors". He had a small role in "It Conquered the World", which he also wrote, as Dr. Pete Shelton. Griffith died on September 28, 2007 in San Diego, aged 77, from undisclosed causes. Quentin Tarantino dedicated his film "Deathproof" to Griffith, whom he referred to as one of his main influences and called "the father of redneck cinema". Passage 8: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 9: S. N. Mathur S.N. Mathur was the Director of the Indian Intelligence Bureau between September 1975 and February 1980. He was also the Director General of Police in Punjab. Passage 10: Jesse E. Hobson Jesse Edward Hobson( May 2, 1911 – November 5, 1970) was the director of SRI International from 1947 to 1955. Prior to SRI, he was the director of the Armour Research Foundation. Question: Where was the director of film Forbidden Island born? Answer: Chicago
{ "task_name": "2WikiMultihopQA" }
Passage 1: Calendula arvensis Calendula arvensis is a species of flowering plant in the daisy family known by the common name field marigold. It is native to central and southern Europe, and it is known across the globe as an introduced species. Passage 2: Calendula Calendula ( ), is a genus of about 15–20 species of annual and perennial herbaceous plants in the daisy family Asteraceae that are often known as marigolds. They are native to southwestern Asia, western Europe, Macaronesia, and the Mediterranean. Other plants are also known as marigolds, such as corn marigold, desert marigold, marsh marigold, and plants of the genus "Tagetes". Passage 3: Purshia stansburyana Purshia stansburyana is a species of flowering plant in the rose family known by the common name Stansbury's cliffrose. It is native to the southwestern United States and northern Mexico, where it grows in woodlands, desert, and plateau habitat. It often grows anchored on cliffs and prefers rocky, granular soils, especially limestone. Passage 4: Purshia Purshia (bitterbrush or cliff-rose) is a small genus of 5-8 species of flowering plants in the family Rosaceae, native to western North America, where they grow in dry climates from southeast British Columbia in Canada south throughout the western United States to northern Mexico. The classification of "Purshia" within the Rosaceae has been unclear. The genus was originally placed in the subfamily Rosoideae, but is now placed in subfamily Dryadoideae. Passage 5: Purshia mexicana Purshia mexicana is a species of perennial flowering small tree in the rose family known by the common name Mexican cliffrose. It is native to western-northern Mexico, the region of the Sierra Madre Occidental cordillera. Passage 6: Calendula maritima Calendula maritima, known as the sea marigold and trailing calendula, is a very rare species from the family of Asteraceae. Some scientists regarded it as "Calendula suffruticosa" subspecies "maritima". Passage 7: Purshia glandulosa Purshia glandulosa is a species of flowering plant in the rose family known by the common names antelope bitterbrush, desert bitterbrush, Mojave antelope brush. Question: Which has more species, Calendula or Purshia? Answer: Calendula
{ "task_name": "hotpotqa" }
Document: A direct marketing company selling “as-seen-on-TV” type products such as Snuggies and the Magic Mesh door cover has agreed to pay $7.5 million to the Federal Trade Commission for consumer restitution to settle FTC charges in connection with its deceptive “buy-one-get-one-free” promotions. The FTC’s settlement with Allstar Marketing Group, LLC, was reached alongside actions by the New York State Office of the Attorney General, which is announcing a separate state case today. In addition to the $7.5 million paid to the FTC, Allstar will pay $500,000 to the Attorney General’s Office for penalties, costs, and fees to settle that action. “Marketers must clearly disclose all costs. That includes processing fees, handling fees, and any other fees they think up,” said Jessica Rich, Director of the FTC’s Bureau of Consumer Protection. “Working with the New York Attorney General, we’ll return millions of dollars to consumers that Allstar collected in undisclosed fees.” “This agreement returns money to thousands of consumers in New York and across the nation who believed they were buying items at the price advertised on television, but ended up with extra merchandise and hidden fees they didn’t bargain for,” Attorney General Eric T. Schneiderman said. “The settlement also brings much needed reforms to a major firm in the direct marketing industry. Those who use small print and hidden fees to inflate charges to unwitting consumers must be held accountable.” According to the FTC’s complaint, since at least 1999, Allstar, based in Hawthorne, New York, has been in the direct marketing business, using television commercials to sell its products, many of which are familiar to consumers such as Magic Mesh, Cat’s Meow, Roto Punch, Perfect Tortilla, Forever Comfy, and Snuggies. While the products have varied, Allstar’s pitch is often the same -- a “buy-one-get-one-free” offer without additional costs disclosed. In a recent commercial for Magic Mesh, for example, the company promised that it would “double the offer” for consumers, if they just paid “processing and handling fees.” While consumers were led to believe that they would then be getting two $19.95 products for “less than $10 each,” in fact, the total cost with the undisclosed $7.95“processing and handling” fees jumped from the advertised price of $19.95 to $35.85, according to the complaint. As alleged in the FTC’s complaint, consumers who called Allstar were often immediately instructed to enter their personal and billing information, and were charged for at least one “set” of products, based on the “buy-one-get-one-free” offer, before they had a chance to indicate how many products they wanted to buy. Because the sales pitch was often confusing, some consumers purchased more “sets” than they actually wanted. Allstar then attempted to upsell consumers additional products via automated voice prompts that requested the consumer accept the offer. Many times, the only way a consumer could decline the offer was to say nothing. At the end of the calls, Allstar sometimes routed consumers to other third-party sellers who made additional sales pitches. Once all of the offers ended, consumers were not told the total number of items they’d “agreed” to buy, or the total amount they would be billed, according to the complaint. The Commission has alleged that Allstar even charged those consumers who hung up mid-call, not intending to complete a sale. According to the FTC’s complaint, consumers who opted to buy Allstars’ products online faced similar problems, including separate “processing and handling” fees which were only disclosed in very fine print at the bottom of the page, and a barrage of upsell offers. Consumers were not provided with the total price of their purchases, and despite a “30 day money-back guarantee” (less processing and handling fees) full refunds were difficult for consumers to obtain. Based on this alleged conduct, the FTC’s complaint charges Allstar with two violations of the FTC Act and three violations of the agency’s Telemarketing Sales Rule (TSR), including the following: Billing consumers without their express informed consent; Failing to make adequate disclosures about the total number and cost of products before billing consumers; In connection with the up-selling of goods and services, violating the TSR by failing to disclose material information about the total cost of the products and that the purpose of the call is to sell goods or services ; and During telemarketing, illegally billing consumers without first getting their consent. The settlement order prohibits Allstar from failing to obtain consumers’ written consent before billing them for any product or service. It also requires the company to clearly and conspicuously disclose – before billing consumers – the total number of products they have ordered, all related fees and costs, and material conditions related to the products purchased. It also prohibits Allstar from violating the TSR by: 1) failing to disclose the true costs of any goods or products it sells; 2) failing to promptly disclose the identity of the seller to consumers and that the purpose of the call is to sell a product or service; and 3) causing billing information to be submitted for payment without consumers’ express authorization. Finally, the order imposes a monetary judgment of $7.5 million, which, in consultation with the New York Attorney General’s Office, may be used to provide refunds to defrauded consumers. The Commission’s vote approving the complaint and the stipulated final order was 5-0. The complaint was filed in the U.S. District Court for the Northern District of Illinois and the stipulated final order submitted to the court for approval. The FTC appreciates the assistance of the New York State Attorney General’s Office in bringing this action. NOTE: The Commission files a complaint when it has “reason to believe” that the law has been or is being violated and it appears to the Commission that a proceeding is in the public interest. Stipulated orders have the force of law when approved and signed by the district court judge. The Federal Trade Commission works for consumers to prevent fraudulent, deceptive, and unfair business practices and to provide information to help spot, stop, and avoid them. To file a complaint in English or Spanish, visit the FTC’s online Complaint Assistant or call 1-877-FTC-HELP (1-877-382-4357). The FTC enters complaints into Consumer Sentinel, a secure, online database available to more than 2,000 civil and criminal law enforcement agencies in the U.S. and abroad. The FTC’s website provides free information on a variety of consumer topics. Like the FTC on Facebook, follow us on Twitter, and subscribe to press releases for the latest FTC news and resources. Consumers with questions about this case can also call the Attorney General’s consumer helpline at 1-800-771-7755. ||||| Firm Behind Snuggies to Pay $8M in Settlement (CN) - Allstar Marketing Group, the company behind such as-seen-on-TV products as Snuggies, Magic Mesh and Car's Meow, will pay $8 million to settle charges it deceived consumers into paying exorbitant processing and handling fees that double the cost of their products, the Federal Trade Commission announced. The settlement includes a $7.5 million payment to the FTC, and a $500,000 payment the New York State Attorney General's office. According to a complaint the agency filed in Chicago Federal Court, Allstar Marketing has been using almost identical television commercials to sell a host of products since 1999. Consumers can buy the advertised products, which also include Roto Punch and the Perfect Tortilla, in retail stores, by phone or online, but in each case the manner in which the company markets and sells its products is similar across product lines, the FTC says. "Defendant's televised commercials for all of its products adhere to a nearly identical script," the complaint says. "The commercial, which generally are approximately two minutes in length, begin by touting the products and their features. Nearly all of Defendant's products offered for purchase by telephone or online include a 'buy-one-get-one-free' promotion." The problem, the agency says, is what comes near the end of the commercials. As an example, it cites the promotion of Magic Mesh, a door-sized screen that is advertised as letting "fresh air in and keeping annoying bugs out." "During the Magic Mesh commercial, the narrator never discloses that Allstar charges $7.95 for "processing and handling" for each Magic Mesh," the complaint says. "Nor does the Narrator disclose that it is not possible to decline the second 'free' Magic Mesh, meaning that the minimum 'processing and handling' fee that the Defendant charges is actually $15.90. "In reality," the complaint continues, Defendant's undisclosed processing and handling fees nearly double the advertised cost of the Magic Mesh from $19.95 to $35.85. Defendant offers many of its other products in a similar manner." The FTC claims that consumers who choose to call the toll-free numbers shown at the end of the commercials are guided through Allstar's interactive voice recognition ordering system, "which is deceptive and misleading." "At the outset, consumers are instructed to input their name and address, followed by their credit or debit card number," the complaint says. "Defendant collects consumers' billing information -- including the credit card or debit number -- before consumers have indicated how many products they are ordering and before Allstar discloses the total cost of consumers' orders." "Despite neither disclosing quantity nor price, however, Defendant immediately charges consumers who enter their billing information for at least one 'set,' which includes the buy-one-get-one-free promotion of the main product being advertised," the agency adds. Once all this takes place, Allstar offers consumers a series of "upsells," additional goods or services offered either by it directly, or by third-parties. "As with the Defendant's main offer, the ordering process for the various upsell offers is deceptive and misleading, and the total cost associated with the upsells is not disclosed during the telephone calls," the complaint says. The FTC claims Allstar employs similarly deceptive practices in its online sales efforts. "Finally, Defendant's refund policy makes it virtually impossible for consumers to receive a full refund for products they never intended to purchase in the first instance," the complaint says. "Defendant's stated refund policy for many of its products is a "30 day money-back guarantee (less P&H)," even though processing and handling can account for nearly half of consumers' purchase cost." According to the FTC, "Consumers have stated that when they have contacted Defendant to complaint of being charged for too many products, Defendant has refused to issue full refunds and has directed consumers to return the unwanted products at consumers' own expense. In other instances, Defendant offers complaining consumers minor discounts in exchange for consumers keeping the unwanted products." The settlement prohibits Allstar from failing to obtain consumers' written consent before billing them for any product or service. It also requires the company to clearly and conspicuously disclose - before billing consumers - the total number of products they have ordered, all related fees and costs, and material conditions related to the products purchased. It also prohibits Allstar from violating the TSR by failing to disclose the true costs of any goods or products it sells; failing to promptly disclose the identity of the seller to consumers and that the purpose of the call is to sell a product or service; and causing billing information to be submitted for payment without consumers' express authorization. After the settlement was announced, Jennifer De Marco, Allstar's General Counsel, released a statement on behalf of the company. "Allstar is pleased to have resolved this matter, and we're proud that it resulted in positive change for our company. One of our goals has always been to provide a positive purchasing experience for our customers," said Jennifer De Marco, General Counsel at Allstar. "While we have always believed our processes complied with the law, we are proud to have successfully worked with the FTC and the NY AG to improve them and set new standards for transparency," the statement said. ||||| That ride, Mr. Blyskal writes, “starts with dramatizations of a problem you didn’t know you had, followed by the incredible solution, then a series of ever more amazing product benefits, bonuses, and giveaways, all leading to the final thrilling plunge of an unbelievably low price.” • Among products the article says are not worth buying are the Snuggie, ShamWow, Debbie Meyer Green Bags for food storage, and the Garry Ultra Light vacuum, which testers said fell short of advertised claims and, even when they had some good attributes, were overpriced. The only two items that passed muster: the PedEgg, a foot file that traps shavings in a compartment and costs about $10, and the Magic Jack, a phone device using voice over Internet protocol. The recession has had a silver lining for direct-response advertisers, who found they could afford to advertise on TV in prime time rather than late at night after banks and automakers curtailed their advertising and ad rates dropped. Photo None of the latest crop of infomercials has been a bigger sensation than the Snuggie, which draws derision and awe in equal measure. It has been mocked by television hosts like Jay Leno, Jon Stewart and Ellen DeGeneres, donned at Snuggie pub crawls across the country, parodied in videos on YouTube, and idolized on Facebook, where the Snuggie page has more than 77,000 fans. In the soon-to-be-published book, “Priceless: The Myth of Fair Value (and How to Take Advantage of It),” the author William Poundstone writes that the central principle of infomercials is what the economist Richard Thaler calls “Don’t wrap all the Christmas presents in one box,” meaning that consumers value freebies that come with a purchased item more than purchasing the same items presented as a set. “Thaler deduced that marketers should devote less energy to promoting how absolutely wonderful their product is, and more to breaking it down, feature by feature, or selling several products in one bundle,” Mr. Poundstone writes. “The one thing you can’t buy in an infomercial is one thing.” Newsletter Sign Up Continue reading the main story Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up You agree to receive occasional updates and special offers for The New York Times's products and services. Thank you for subscribing. An error has occurred. Please try again later. View all New York Times newsletters. The Snuggie infomercial first plugs the sleeved blanket, then throws in a free book light, announcing the price is $19.95, plus $7.95 for postage and handling, then adds that a buyer also will receive a second Snuggie and second book light for an additional $7.95 for postage and handling. It was compulsory to order two Snuggies and two book lights for a total of $35.85, plus tax, though that actual price was never mentioned. Although now also offered by retailers like Walgreens, the Snuggie is still applauded by direct marketers. In September, Allstar Marketing Group of Hawthorne, N.Y., which markets the Snuggie and other products like the children’s toy Bendaroos, was named marketer of the year by Direct Response Marketing Alliance, a trade group. Advertisement Continue reading the main story Consumer Reports, however, was not impressed. Testers complained that the Snuggie was so cumbersome that walking in it was difficult, that its sleeves, despite being marketed as “perfect for men, women and children,” were too long for shorter adult testers, and that the gaping opening in the back “left their backside uncovered, though it kept other parts toasty.” The magazine also washed the Snuggies, advertised as having “ultrasoft thick luxurious fleece.” The article stated, “Each time we laundered two Snuggies, we removed a sandwich bag’s worth of lint from the dryer screen. After 10 washings, “the fabric had bare spots between pills and clumps.” • When asked to comment on the Consumer Reports article, Allstar said in a written statement that, “We stand behind the Snuggie 100 percent. More than 20 million people have purchased a Snuggie blanket and we frequently receive comments from consumers telling us they love their Snuggie.” As for the laundering, “all blankets shed to an extent when being laundered,” the statement continued. “Because the Snuggie is designed to be used like a blanket, you typically don’t have to wash it as often as you would clothing.” Consumer Reports has 3.9 million subscribers and newsstand sales of 140,000, but how much its opinion of the Snuggie will sting is an open question. “It will certainly hurt the people who are going to read Consumer Reports to decide if they want to buy a Snuggie,” said Mr. Poundstone, the author. “But that’s a pretty small segment of the Snuggie audience, I would think.” Summary: – If you have a Snuggie stuffed away in a drawer, you may have been had, at least according to the Federal Trade Commission. Snuggie maker Allstar Marketing Group has settled with the FTC to the tune of $7.5 million over allegations that the as-seen-on-TV company levied unreasonable "processing and handling" fees—without disclosing them to the buyer. Courthouse News reports that the complaint (which a rep for Allstar explains was filed yesterday in order to enter the settlement agreement) used the Magic Mesh product as an example. The product lets "fresh air in and [keeps] annoying bugs out," but nowhere in the commercial for it is mention made of the $7.95 processing and handling fee. Further, almost all of Allstar's products are promoted as "buy-one-get-one-free"; buyers are obligated to get two, "meaning that the minimum 'processing and handling' fee that the Defendant charges is actually $15.90." What that means for the buyer: Those $19.95 Magic Meshes will cost $35.85 plus tax, and "Defendant offers many of its other products in a similar manner." It's not exactly a new revelation: A 2010 New York Times article noted that Snuggie buyers had to get two, again for a total of $35.85, not $19.95, "though that actual price was never mentioned." In its claim, the FTC also alleged that the "Defendant's refund policy makes it virtually impossible for consumers to receive a full refund for products they never intended to purchase in the first instance," as the processing and handling fees are not refunded. In a press release, the FTC explains Allstar will have to make clear how many products a customer is ordering, and at what cost, before the customer is billed. Allstar will pay another $500,000 to the New York State Office of the Attorney General to settle a separate state case. The money can be used to refund defrauded customers; indeed, a rep for the FTC says "we’ll return millions of dollars to consumers that Allstar collected in undisclosed fees."
{ "task_name": "multi_news" }
package nxt.user; import nxt.Account; import nxt.Block; import nxt.BlockchainProcessor; import nxt.Constants; import nxt.Generator; import nxt.Nxt; import nxt.Transaction; import nxt.TransactionProcessor; import nxt.peer.Peer; import nxt.peer.Peers; import nxt.util.Convert; import nxt.util.Listener; import nxt.util.Logger; import nxt.util.ThreadPool; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.FilterMapping; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; public final class Users { private static final int TESTNET_UI_PORT=6875; private static final ConcurrentMap<String, User> users = new ConcurrentHashMap<>(); private static final Collection<User> allUsers = Collections.unmodifiableCollection(users.values()); private static final AtomicInteger peerCounter = new AtomicInteger(); private static final ConcurrentMap<String, Integer> peerIndexMap = new ConcurrentHashMap<>(); private static final ConcurrentMap<Integer, String> peerAddressMap = new ConcurrentHashMap<>(); private static final AtomicInteger blockCounter = new AtomicInteger(); private static final ConcurrentMap<Long, Integer> blockIndexMap = new ConcurrentHashMap<>(); private static final AtomicInteger transactionCounter = new AtomicInteger(); private static final ConcurrentMap<Long, Integer> transactionIndexMap = new ConcurrentHashMap<>(); static final Set<String> allowedUserHosts; private static final Server userServer; static { List<String> allowedUserHostsList = Nxt.getStringListProperty("nxt.allowedUserHosts"); if (! allowedUserHostsList.contains("*")) { allowedUserHosts = Collections.unmodifiableSet(new HashSet<>(allowedUserHostsList)); } else { allowedUserHosts = null; } boolean enableUIServer = Nxt.getBooleanProperty("nxt.enableUIServer"); if (enableUIServer) { final int port = Constants.isTestnet ? TESTNET_UI_PORT : Nxt.getIntProperty("nxt.uiServerPort"); final String host = Nxt.getStringProperty("nxt.uiServerHost"); userServer = new Server(); ServerConnector connector; boolean enableSSL = Nxt.getBooleanProperty("nxt.uiSSL"); if (enableSSL) { Logger.logMessage("Using SSL (https) for the user interface server"); HttpConfiguration https_config = new HttpConfiguration(); https_config.setSecureScheme("https"); https_config.setSecurePort(port); https_config.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(Nxt.getStringProperty("nxt.keyStorePath")); sslContextFactory.setKeyStorePassword(Nxt.getStringProperty("nxt.keyStorePassword")); sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); connector = new ServerConnector(userServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); } else { connector = new ServerConnector(userServer); } connector.setPort(port); connector.setHost(host); connector.setIdleTimeout(Nxt.getIntProperty("nxt.uiServerIdleTimeout")); userServer.addConnector(connector); HandlerList userHandlers = new HandlerList(); ResourceHandler userFileHandler = new ResourceHandler(); userFileHandler.setDirectoriesListed(false); userFileHandler.setWelcomeFiles(new String[]{"index.html"}); userFileHandler.setResourceBase(Nxt.getStringProperty("nxt.uiResourceBase")); userHandlers.addHandler(userFileHandler); String javadocResourceBase = Nxt.getStringProperty("nxt.javadocResourceBase"); if (javadocResourceBase != null) { ContextHandler contextHandler = new ContextHandler("/doc"); ResourceHandler docFileHandler = new ResourceHandler(); docFileHandler.setDirectoriesListed(false); docFileHandler.setWelcomeFiles(new String[]{"index.html"}); docFileHandler.setResourceBase(javadocResourceBase); contextHandler.setHandler(docFileHandler); userHandlers.addHandler(contextHandler); } ServletHandler userHandler = new ServletHandler(); ServletHolder userHolder = userHandler.addServletWithMapping(UserServlet.class, "/nxt"); userHolder.setAsyncSupported(true); if (Nxt.getBooleanProperty("nxt.uiServerCORS")) { FilterHolder filterHolder = userHandler.addFilterWithMapping(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT); filterHolder.setInitParameter("allowedHeaders", "*"); filterHolder.setAsyncSupported(true); } userHandlers.addHandler(userHandler); userHandlers.addHandler(new DefaultHandler()); userServer.setHandler(userHandlers); userServer.setStopAtShutdown(true); ThreadPool.runBeforeStart(new Runnable() { @Override public void run() { try { userServer.start(); Logger.logMessage("Started user interface server at " + host + ":" + port); } catch (Exception e) { Logger.logDebugMessage("Failed to start user interface server", e); throw new RuntimeException(e.toString(), e); } } }); } else { userServer = null; Logger.logMessage("User interface server not enabled"); } } static { if (userServer != null) { Account.addListener(new Listener<Account>() { @Override public void notify(Account account) { JSONObject response = new JSONObject(); response.put("response", "setBalance"); response.put("balanceNQT", account.getUnconfirmedBalanceNQT()); byte[] accountPublicKey = account.getPublicKey(); for (User user : Users.users.values()) { if (user.getSecretPhrase() != null && Arrays.equals(user.getPublicKey(), accountPublicKey)) { user.send(response); } } } }, Account.Event.UNCONFIRMED_BALANCE); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray removedActivePeers = new JSONArray(); JSONObject removedActivePeer = new JSONObject(); removedActivePeer.put("index", Users.getIndex(peer)); removedActivePeers.add(removedActivePeer); response.put("removedActivePeers", removedActivePeers); JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Users.getIndex(peer)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); JSONArray addedBlacklistedPeers = new JSONArray(); JSONObject addedBlacklistedPeer = new JSONObject(); addedBlacklistedPeer.put("index", Users.getIndex(peer)); addedBlacklistedPeer.put("address", peer.getPeerAddress()); addedBlacklistedPeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { addedBlacklistedPeer.put("wellKnown", true); } addedBlacklistedPeer.put("software", peer.getSoftware()); addedBlacklistedPeers.add(addedBlacklistedPeer); response.put("addedBlacklistedPeers", addedBlacklistedPeers); Users.sendNewDataToAll(response); } }, Peers.Event.BLACKLIST); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray removedActivePeers = new JSONArray(); JSONObject removedActivePeer = new JSONObject(); removedActivePeer.put("index", Users.getIndex(peer)); removedActivePeers.add(removedActivePeer); response.put("removedActivePeers", removedActivePeers); JSONArray addedKnownPeers = new JSONArray(); JSONObject addedKnownPeer = new JSONObject(); addedKnownPeer.put("index", Users.getIndex(peer)); addedKnownPeer.put("address", peer.getPeerAddress()); addedKnownPeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { addedKnownPeer.put("wellKnown", true); } addedKnownPeer.put("software", peer.getSoftware()); addedKnownPeers.add(addedKnownPeer); response.put("addedKnownPeers", addedKnownPeers); Users.sendNewDataToAll(response); } }, Peers.Event.DEACTIVATE); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray removedBlacklistedPeers = new JSONArray(); JSONObject removedBlacklistedPeer = new JSONObject(); removedBlacklistedPeer.put("index", Users.getIndex(peer)); removedBlacklistedPeers.add(removedBlacklistedPeer); response.put("removedBlacklistedPeers", removedBlacklistedPeers); JSONArray addedKnownPeers = new JSONArray(); JSONObject addedKnownPeer = new JSONObject(); addedKnownPeer.put("index", Users.getIndex(peer)); addedKnownPeer.put("address", peer.getPeerAddress()); addedKnownPeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { addedKnownPeer.put("wellKnown", true); } addedKnownPeer.put("software", peer.getSoftware()); addedKnownPeers.add(addedKnownPeer); response.put("addedKnownPeers", addedKnownPeers); Users.sendNewDataToAll(response); } }, Peers.Event.UNBLACKLIST); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Users.getIndex(peer)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); Users.sendNewDataToAll(response); } }, Peers.Event.REMOVE); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Users.getIndex(peer)); changedActivePeer.put("downloaded", peer.getDownloadedVolume()); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); Users.sendNewDataToAll(response); } }, Peers.Event.DOWNLOADED_VOLUME); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Users.getIndex(peer)); changedActivePeer.put("uploaded", peer.getUploadedVolume()); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); Users.sendNewDataToAll(response); } }, Peers.Event.UPLOADED_VOLUME); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Users.getIndex(peer)); changedActivePeer.put("weight", peer.getWeight()); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); Users.sendNewDataToAll(response); } }, Peers.Event.WEIGHT); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Users.getIndex(peer)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); JSONArray addedActivePeers = new JSONArray(); JSONObject addedActivePeer = new JSONObject(); addedActivePeer.put("index", Users.getIndex(peer)); if (peer.getState() != Peer.State.CONNECTED) { addedActivePeer.put("disconnected", true); } addedActivePeer.put("address", peer.getPeerAddress()); addedActivePeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { addedActivePeer.put("wellKnown", true); } addedActivePeer.put("weight", peer.getWeight()); addedActivePeer.put("downloaded", peer.getDownloadedVolume()); addedActivePeer.put("uploaded", peer.getUploadedVolume()); addedActivePeer.put("software", peer.getSoftware()); addedActivePeers.add(addedActivePeer); response.put("addedActivePeers", addedActivePeers); Users.sendNewDataToAll(response); } }, Peers.Event.ADDED_ACTIVE_PEER); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Users.getIndex(peer)); changedActivePeer.put(peer.getState() == Peer.State.CONNECTED ? "connected" : "disconnected", true); changedActivePeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { changedActivePeer.put("wellKnown", true); } changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); Users.sendNewDataToAll(response); } }, Peers.Event.CHANGED_ACTIVE_PEER); Peers.addListener(new Listener<Peer>() { @Override public void notify(Peer peer) { JSONObject response = new JSONObject(); JSONArray addedKnownPeers = new JSONArray(); JSONObject addedKnownPeer = new JSONObject(); addedKnownPeer.put("index", Users.getIndex(peer)); addedKnownPeer.put("address", peer.getPeerAddress()); addedKnownPeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true)); if (peer.isWellKnown()) { addedKnownPeer.put("wellKnown", true); } addedKnownPeer.put("software", peer.getSoftware()); addedKnownPeers.add(addedKnownPeer); response.put("addedKnownPeers", addedKnownPeers); Users.sendNewDataToAll(response); } }, Peers.Event.NEW_PEER); Nxt.getTransactionProcessor().addListener(new Listener<List<Transaction>>() { @Override public void notify(List<Transaction> transactions) { JSONObject response = new JSONObject(); JSONArray removedUnconfirmedTransactions = new JSONArray(); for (Transaction transaction : transactions) { JSONObject removedUnconfirmedTransaction = new JSONObject(); removedUnconfirmedTransaction.put("index", Users.getIndex(transaction)); removedUnconfirmedTransactions.add(removedUnconfirmedTransaction); } response.put("removedUnconfirmedTransactions", removedUnconfirmedTransactions); Users.sendNewDataToAll(response); } }, TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS); Nxt.getTransactionProcessor().addListener(new Listener<List<Transaction>>() { @Override public void notify(List<Transaction> transactions) { JSONObject response = new JSONObject(); JSONArray addedUnconfirmedTransactions = new JSONArray(); for (Transaction transaction : transactions) { JSONObject addedUnconfirmedTransaction = new JSONObject(); addedUnconfirmedTransaction.put("index", Users.getIndex(transaction)); addedUnconfirmedTransaction.put("timestamp", transaction.getTimestamp()); addedUnconfirmedTransaction.put("deadline", transaction.getDeadline()); addedUnconfirmedTransaction.put("recipient", Convert.toUnsignedLong(transaction.getRecipientId())); addedUnconfirmedTransaction.put("amountNQT", transaction.getAmountNQT()); addedUnconfirmedTransaction.put("feeNQT", transaction.getFeeNQT()); addedUnconfirmedTransaction.put("sender", Convert.toUnsignedLong(transaction.getSenderId())); addedUnconfirmedTransaction.put("id", transaction.getStringId()); addedUnconfirmedTransactions.add(addedUnconfirmedTransaction); } response.put("addedUnconfirmedTransactions", addedUnconfirmedTransactions); Users.sendNewDataToAll(response); } }, TransactionProcessor.Event.ADDED_UNCONFIRMED_TRANSACTIONS); Nxt.getTransactionProcessor().addListener(new Listener<List<Transaction>>() { @Override public void notify(List<Transaction> transactions) { JSONObject response = new JSONObject(); JSONArray addedConfirmedTransactions = new JSONArray(); for (Transaction transaction : transactions) { JSONObject addedConfirmedTransaction = new JSONObject(); addedConfirmedTransaction.put("index", Users.getIndex(transaction)); addedConfirmedTransaction.put("blockTimestamp", transaction.getBlockTimestamp()); addedConfirmedTransaction.put("transactionTimestamp", transaction.getTimestamp()); addedConfirmedTransaction.put("sender", Convert.toUnsignedLong(transaction.getSenderId())); addedConfirmedTransaction.put("recipient", Convert.toUnsignedLong(transaction.getRecipientId())); addedConfirmedTransaction.put("amountNQT", transaction.getAmountNQT()); addedConfirmedTransaction.put("feeNQT", transaction.getFeeNQT()); addedConfirmedTransaction.put("id", transaction.getStringId()); addedConfirmedTransactions.add(addedConfirmedTransaction); } response.put("addedConfirmedTransactions", addedConfirmedTransactions); Users.sendNewDataToAll(response); } }, TransactionProcessor.Event.ADDED_CONFIRMED_TRANSACTIONS); Nxt.getTransactionProcessor().addListener(new Listener<List<Transaction>>() { @Override public void notify(List<Transaction> transactions) { JSONObject response = new JSONObject(); JSONArray newTransactions = new JSONArray(); for (Transaction transaction : transactions) { JSONObject newTransaction = new JSONObject(); newTransaction.put("index", Users.getIndex(transaction)); newTransaction.put("timestamp", transaction.getTimestamp()); newTransaction.put("deadline", transaction.getDeadline()); newTransaction.put("recipient", Convert.toUnsignedLong(transaction.getRecipientId())); newTransaction.put("amountNQT", transaction.getAmountNQT()); newTransaction.put("feeNQT", transaction.getFeeNQT()); newTransaction.put("sender", Convert.toUnsignedLong(transaction.getSenderId())); newTransaction.put("id", transaction.getStringId()); newTransactions.add(newTransaction); } response.put("addedDoubleSpendingTransactions", newTransactions); Users.sendNewDataToAll(response); } }, TransactionProcessor.Event.ADDED_DOUBLESPENDING_TRANSACTIONS); Nxt.getBlockchainProcessor().addListener(new Listener<Block>() { @Override public void notify(Block block) { JSONObject response = new JSONObject(); JSONArray addedOrphanedBlocks = new JSONArray(); JSONObject addedOrphanedBlock = new JSONObject(); addedOrphanedBlock.put("index", Users.getIndex(block)); addedOrphanedBlock.put("timestamp", block.getTimestamp()); addedOrphanedBlock.put("numberOfTransactions", block.getTransactionIds().size()); addedOrphanedBlock.put("totalAmountNQT", block.getTotalAmountNQT()); addedOrphanedBlock.put("totalFeeNQT", block.getTotalFeeNQT()); addedOrphanedBlock.put("payloadLength", block.getPayloadLength()); addedOrphanedBlock.put("generator", Convert.toUnsignedLong(block.getGeneratorId())); addedOrphanedBlock.put("height", block.getHeight()); addedOrphanedBlock.put("version", block.getVersion()); addedOrphanedBlock.put("block", block.getStringId()); addedOrphanedBlock.put("baseTarget", BigInteger.valueOf(block.getBaseTarget()).multiply(BigInteger.valueOf(100000)).divide(BigInteger.valueOf(Constants.INITIAL_BASE_TARGET))); addedOrphanedBlocks.add(addedOrphanedBlock); response.put("addedOrphanedBlocks", addedOrphanedBlocks); Users.sendNewDataToAll(response); } }, BlockchainProcessor.Event.BLOCK_POPPED); Nxt.getBlockchainProcessor().addListener(new Listener<Block>() { @Override public void notify(Block block) { JSONObject response = new JSONObject(); JSONArray addedRecentBlocks = new JSONArray(); JSONObject addedRecentBlock = new JSONObject(); addedRecentBlock.put("index", Users.getIndex(block)); addedRecentBlock.put("timestamp", block.getTimestamp()); addedRecentBlock.put("numberOfTransactions", block.getTransactionIds().size()); addedRecentBlock.put("totalAmountNQT", block.getTotalAmountNQT()); addedRecentBlock.put("totalFeeNQT", block.getTotalFeeNQT()); addedRecentBlock.put("payloadLength", block.getPayloadLength()); addedRecentBlock.put("generator", Convert.toUnsignedLong(block.getGeneratorId())); addedRecentBlock.put("height", block.getHeight()); addedRecentBlock.put("version", block.getVersion()); addedRecentBlock.put("block", block.getStringId()); addedRecentBlock.put("baseTarget", BigInteger.valueOf(block.getBaseTarget()).multiply(BigInteger.valueOf(100000)).divide(BigInteger.valueOf(Constants.INITIAL_BASE_TARGET))); addedRecentBlocks.add(addedRecentBlock); response.put("addedRecentBlocks", addedRecentBlocks); Users.sendNewDataToAll(response); } }, BlockchainProcessor.Event.BLOCK_PUSHED); Generator.addListener(new Listener<Generator>() { @Override public void notify(Generator generator) { JSONObject response = new JSONObject(); response.put("response", "setBlockGenerationDeadline"); response.put("deadline", generator.getDeadline()); for (User user : users.values()) { if (Arrays.equals(generator.getPublicKey(), user.getPublicKey())) { user.send(response); } } } }, Generator.Event.GENERATION_DEADLINE); } } static Collection<User> getAllUsers() { return allUsers; } static User getUser(String userId) { User user = users.get(userId); if (user == null) { user = new User(userId); User oldUser = users.putIfAbsent(userId, user); if (oldUser != null) { user = oldUser; user.setInactive(false); } } else { user.setInactive(false); } return user; } static User remove(User user) { return users.remove(user.getUserId()); } private static void sendNewDataToAll(JSONObject response) { response.put("response", "processNewData"); sendToAll(response); } private static void sendToAll(JSONStreamAware response) { for (User user : users.values()) { user.send(response); } } static int getIndex(Peer peer) { Integer index = peerIndexMap.get(peer.getPeerAddress()); if (index == null) { index = peerCounter.incrementAndGet(); peerIndexMap.put(peer.getPeerAddress(), index); peerAddressMap.put(index, peer.getPeerAddress()); } return index; } static Peer getPeer(int index) { String peerAddress = peerAddressMap.get(index); if (peerAddress == null) { return null; } return Peers.getPeer(peerAddress); } static int getIndex(Block block) { Integer index = blockIndexMap.get(block.getId()); if (index == null) { index = blockCounter.incrementAndGet(); blockIndexMap.put(block.getId(), index); } return index; } static int getIndex(Transaction transaction) { Integer index = transactionIndexMap.get(transaction.getId()); if (index == null) { index = transactionCounter.incrementAndGet(); transactionIndexMap.put(transaction.getId(), index); } return index; } public static void init() {} public static void shutdown() { if (userServer != null) { try { userServer.stop(); } catch (Exception e) { Logger.logDebugMessage("Failed to stop user interface server", e); } } } private Users() {} // never }
{ "task_name": "lcc" }
# -*- coding: utf-8 -*- from functools import update_wrapper import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from django.utils.six.moves.urllib.parse import urljoin from cms import constants __all__ = ['get_cms_setting'] class VERIFIED: pass # need a unique identifier for CMS_LANGUAGES def default(name): def decorator(wrapped): def wrapper(): if hasattr(settings, name): return getattr(settings, name) return wrapped() update_wrapper(wrapper, wrapped) return wrapped return decorator DEFAULTS = { 'TEMPLATE_INHERITANCE': True, 'TOOLBAR_SIMPLE_STRUCTURE_MODE': True, 'PLACEHOLDER_CONF': {}, 'PERMISSION': False, # Whether to use raw ID lookups for users when PERMISSION is True 'RAW_ID_USERS': False, 'PUBLIC_FOR': 'all', 'APPHOOKS': [], 'TOOLBARS': [], 'SITE_CHOICES_CACHE_KEY': 'CMS:site_choices', 'PAGE_CHOICES_CACHE_KEY': 'CMS:page_choices', 'MEDIA_PATH': 'cms/', 'PAGE_MEDIA_PATH': 'cms_page_media/', 'TITLE_CHARACTER': '+', 'PAGE_CACHE': True, 'PLACEHOLDER_CACHE': True, 'PLUGIN_CACHE': True, 'CACHE_PREFIX': 'cms-', 'PLUGIN_PROCESSORS': [], 'PLUGIN_CONTEXT_PROCESSORS': [], 'UNIHANDECODE_VERSION': None, 'UNIHANDECODE_DECODERS': ['ja', 'zh', 'kr', 'vn', 'diacritic'], 'UNIHANDECODE_DEFAULT_DECODER': 'diacritic', 'MAX_PAGE_PUBLISH_REVERSIONS': 10, 'MAX_PAGE_HISTORY_REVERSIONS': 15, 'TOOLBAR_ANONYMOUS_ON': True, 'TOOLBAR_URL__EDIT_ON': 'edit', 'TOOLBAR_URL__EDIT_OFF': 'edit_off', 'TOOLBAR_URL__BUILD': 'build', 'TOOLBAR_URL__DISABLE': 'toolbar_off', 'ADMIN_NAMESPACE': 'admin', 'TOOLBAR_HIDE': False, 'WIZARD_DEFAULT_TEMPLATE': constants.TEMPLATE_INHERITANCE_MAGIC, 'WIZARD_CONTENT_PLUGIN': 'TextPlugin', 'WIZARD_CONTENT_PLUGIN_BODY': 'body', } def get_cache_durations(): """ Returns the setting: CMS_CACHE_DURATIONS or the defaults. """ return getattr(settings, 'CMS_CACHE_DURATIONS', { 'menus': 60 * 60, 'content': 60, 'permissions': 60 * 60, }) @default('CMS_MEDIA_ROOT') def get_media_root(): return os.path.join(settings.MEDIA_ROOT, get_cms_setting('MEDIA_PATH')) @default('CMS_MEDIA_URL') def get_media_url(): return urljoin(settings.MEDIA_URL, get_cms_setting('MEDIA_PATH')) @default('CMS_TOOLBAR_URL__EDIT_ON') def get_toolbar_url__edit_on(): return get_cms_setting('TOOLBAR_URL__EDIT_ON') @default('CMS_TOOLBAR_URL__EDIT_OFF') def get_toolbar_url__edit_off(): return get_cms_setting('TOOLBAR_URL__EDIT_OFF') @default('CMS_TOOLBAR_URL__BUILD') def get_toolbar_url__build(): return get_cms_setting('TOOLBAR_URL__BUILD') @default('CMS_TOOLBAR_URL__DISABLE') def get_toolbar_url__disable(): return get_cms_setting('TOOLBAR_URL__DISABLE') def get_templates(): from cms.utils.django_load import load_from_file if getattr(settings, 'CMS_TEMPLATES_DIR', False): tpldir = getattr(settings, 'CMS_TEMPLATES_DIR', False) # CMS_TEMPLATES_DIR can either be a string poiting to the templates directory # or a dictionary holding 'site: template dir' entries if isinstance(tpldir, dict): tpldir = tpldir[settings.SITE_ID] # We must extract the relative path of CMS_TEMPLATES_DIR to the neares # valid templates directory. Here we mimick what the filesystem and # app_directories template loaders do prefix = '' # Relative to TEMPLATE_DIRS for filesystem loader try: path = settings.TEMPLATE_DIRS except IndexError: path = [template['DIRS'][0] for template in settings.TEMPLATES] for basedir in path: if tpldir.find(basedir) == 0: prefix = tpldir.replace(basedir + os.sep, '') break # Relative to 'templates' directory that app_directory scans if not prefix: components = tpldir.split(os.sep) try: prefix = os.path.join(*components[components.index('templates') + 1:]) except ValueError: # If templates is not found we use the directory name as prefix # and hope for the best prefix = os.path.basename(tpldir) config_path = os.path.join(tpldir, '__init__.py') # Try to load templates list and names from the template module # If module file is not present skip configuration and just dump the filenames as templates if config_path: template_module = load_from_file(config_path) templates = [(os.path.join(prefix, data[0].strip()), data[1]) for data in template_module.TEMPLATES.items()] else: templates = list((os.path.join(prefix, tpl), tpl) for tpl in os.listdir(tpldir)) else: templates = list(getattr(settings, 'CMS_TEMPLATES', [])) if get_cms_setting('TEMPLATE_INHERITANCE'): templates.append((constants.TEMPLATE_INHERITANCE_MAGIC, _('Inherit the template of the nearest ancestor'))) return templates def _ensure_languages_settings(languages): valid_language_keys = ['code', 'name', 'fallbacks', 'hide_untranslated', 'redirect_on_fallback', 'public'] required_language_keys = ['code', 'name'] simple_defaults = ['public', 'redirect_on_fallback', 'hide_untranslated'] if not isinstance(languages, dict): raise ImproperlyConfigured( "CMS_LANGUAGES must be a dictionary with site IDs and 'default'" " as keys. Please check the format.") defaults = languages.pop('default', {}) default_fallbacks = defaults.get('fallbacks') needs_fallbacks = [] for key in defaults: if key not in valid_language_keys: raise ImproperlyConfigured("CMS_LANGUAGES has an invalid property in the default properties: %s" % key) for key in simple_defaults: if key not in defaults: defaults[key] = True for site, language_list in languages.items(): if site != hash(site): raise ImproperlyConfigured( "CMS_LANGUAGES can only be filled with integers (site IDs) and 'default'" " for default values. %s is not a valid key." % site) for language_object in language_list: for required_key in required_language_keys: if required_key not in language_object: raise ImproperlyConfigured("CMS_LANGUAGES has a language which is missing the required key %r " "in site %r" % (key, site)) language_code = language_object['code'] for key in language_object: if key not in valid_language_keys: raise ImproperlyConfigured( "CMS_LANGUAGES has invalid key %r in language %r in site %r" % (key, language_code, site) ) if 'fallbacks' not in language_object: if default_fallbacks: language_object['fallbacks'] = default_fallbacks else: needs_fallbacks.append((site, language_object)) for key in simple_defaults: if key not in language_object: language_object[key] = defaults[key] site_fallbacks = {} for site, language_object in needs_fallbacks: if site not in site_fallbacks: site_fallbacks[site] = [lang['code'] for lang in languages[site] if lang['public']] language_object['fallbacks'] = [lang_code for lang_code in site_fallbacks[site] if lang_code != language_object['code']] languages['default'] = defaults languages[VERIFIED] = True # this will be busted by @override_settings and cause a re-check return languages def get_languages(): if settings.SITE_ID != hash(settings.SITE_ID): raise ImproperlyConfigured( "SITE_ID must be an integer" ) if not settings.USE_I18N: return _ensure_languages_settings( {settings.SITE_ID: [{'code': settings.LANGUAGE_CODE, 'name': settings.LANGUAGE_CODE}]}) if settings.LANGUAGE_CODE not in dict(settings.LANGUAGES): raise ImproperlyConfigured( 'LANGUAGE_CODE "%s" must have a matching entry in LANGUAGES' % settings.LANGUAGE_CODE ) languages = getattr(settings, 'CMS_LANGUAGES', { settings.SITE_ID: [{'code': code, 'name': _(name)} for code, name in settings.LANGUAGES] }) if VERIFIED in languages: return languages return _ensure_languages_settings(languages) def get_unihandecode_host(): host = getattr(settings, 'CMS_UNIHANDECODE_HOST', None) if not host: return host if host.endswith('/'): return host else: return host + '/' COMPLEX = { 'CACHE_DURATIONS': get_cache_durations, 'MEDIA_ROOT': get_media_root, 'MEDIA_URL': get_media_url, # complex because not prefixed by CMS_ 'TEMPLATES': get_templates, 'LANGUAGES': get_languages, 'UNIHANDECODE_HOST': get_unihandecode_host, 'CMS_TOOLBAR_URL__EDIT_ON': get_toolbar_url__edit_on, 'CMS_TOOLBAR_URL__EDIT_OFF': get_toolbar_url__edit_off, 'CMS_TOOLBAR_URL__BUILD': get_toolbar_url__build, 'CMS_TOOLBAR_URL__DISABLE': get_toolbar_url__disable, } def get_cms_setting(name): if name in COMPLEX: return COMPLEX[name]() else: return getattr(settings, 'CMS_%s' % name, DEFAULTS[name]) def get_site_id(site): from django.contrib.sites.models import Site if isinstance(site, Site): return site.id try: return int(site) except (TypeError, ValueError): pass return settings.SITE_ID
{ "task_name": "lcc" }
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for depthwise convolutional operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import nn_impl from tensorflow.python.ops import nn_ops import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging def ConfigsToTest(): """Iterator for different convolution shapes, strides and paddings. Yields: Tuple (input_size, filter_size, out_size, stride, padding), the depthwise convolution parameters. """ input_sizes = [[4, 5, 5, 48], [4, 8, 8, 84], [4, 17, 17, 48], [4, 9, 27, 8], [4, 31, 31, 7], [4, 35, 35, 2], [4, 147, 147, 2], [3, 299, 299, 3], [5, 183, 183, 1]] filter_sizes = [[1, 1, 48, 2], [1, 3, 84, 1], [3, 1, 48, 4], [3, 3, 8, 1], [3, 3, 7, 1], [5, 5, 2, 1], [3, 3, 2, 8], [2, 2, 3, 8], [5, 5, 1, 2]] out_sizes = [[4, 5, 5, 96], [4, 8, 8, 84], [4, 17, 17, 192], [4, 9, 27, 8], [4, 31, 31, 7], [4, 35, 35, 2], [4, 49, 49, 16], [3, 150, 150, 24], [5, 92, 92, 2]] strides = [1, 1, 1, 1, 1, 1, 3, 2, 2] # pylint: disable=invalid-name VALID = "VALID" SAME = "SAME" # pylint: enable=invalid-name paddings = [SAME, SAME, SAME, SAME, SAME, SAME, VALID, SAME, SAME, SAME] for i, f, o, s, p in zip(input_sizes, filter_sizes, out_sizes, strides, paddings): yield i, f, o, s, p def CheckGradConfigsToTest(): """Iterator for different convolution shapes, strides and paddings. compute_gradient_error() is very expensive. So the configs should be relatively small. Yields: Tuple (input_size, filter_size, out_size, stride, padding), the depthwise convolution parameters. """ input_sizes = [[2, 5, 8, 1], [4, 5, 5, 1], [2, 4, 4, 2], [1, 15, 15, 2], [2, 15, 16, 1]] filter_sizes = [[4, 4, 1, 2], [2, 2, 1, 2], [3, 1, 2, 2], [1, 3, 2, 1], [3, 3, 1, 2]] out_sizes = [[2, 5, 8, 2], [4, 2, 2, 2], [2, 4, 4, 4], [1, 15, 15, 2], [2, 5, 5, 2]] strides = [1, 2, 1, 1, 3] # pylint: disable=invalid-name VALID = "VALID" SAME = "SAME" # pylint: enable=invalid-name paddings = [SAME, VALID, SAME, SAME, VALID] for i, f, o, s, p in zip(input_sizes, filter_sizes, out_sizes, strides, paddings): yield i, f, o, s, p class DepthwiseConv2DTest(test.TestCase): # This is testing that depthwise_conv2d and depthwise_conv2d_native # produce the same results. It also tests that NCHW and NHWC # formats agree, by comparing the depthwise_conv2d_native with # 'NCHW' format (with transposition) matches the 'NHWC' format using # the higher level interface. def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, data_type, use_gpu, grouped_conv=False, data_format="NHWC"): """Verifies the output values of the convolution function. Args: tensor_in_sizes: Input tensor dimensions in [batch, input_rows, input_cols, input_depth]. filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, input_depth, depth_multiplier]. stride: Stride. padding: Padding type. data_type: The data type to use. use_gpu: Whether to use GPU. grouped_conv: Whether to use cuDNN 7's grouped convolution. data_format: The data_format of the input. "NHWC" or "NCHW". """ input_size = 1 filter_size = 1 for s in tensor_in_sizes: input_size *= s for s in filter_in_sizes: filter_size *= s # Initializes the input and filter tensor with numbers incrementing from 1. x1 = [f * 1.0 / input_size for f in range(1, input_size + 1)] x2 = [f * 1.0 / filter_size for f in range(1, filter_size + 1)] ops.reset_default_graph() graph = ops.get_default_graph() with self.session(graph=graph, use_gpu=use_gpu) as sess: tolerance = { dtypes.float16: 4e-2, dtypes.float32: 1e-5, dtypes.float64: 1e-12, }[data_type] t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=data_type) t1.set_shape(tensor_in_sizes) t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=data_type) native_t1 = t1 strides = [1, stride, stride, 1] if data_format == "NCHW": # Transpose from NHWC input to NCHW # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] native_t1 = array_ops.transpose(t1, [0, 3, 1, 2]) strides = [1, 1, stride, stride] with sess.graph._kernel_label_map({ "DepthwiseConv2dNative": "cudnn_grouped_convolution" } if grouped_conv else {}): conv_native = nn_ops.depthwise_conv2d_native( native_t1, t2, strides=strides, data_format=data_format, padding=padding) if data_format == "NCHW": # Transpose back from NCHW to NHWC conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1]) try: native_result = sess.run(conv_native) except errors.InvalidArgumentError as e: # Grouped convolution kernel is only registered for cuDNN 7. Silently # return when we are running on an earlier version or without GPU. if e.message.startswith( "No OpKernel was registered to support Op 'DepthwiseConv2dNative'"): tf_logging.warn("Skipping grouped convolution test") return raise e conv_interface = nn_impl.depthwise_conv2d( t1, t2, strides=[1, stride, stride, 1], padding=padding) interface_result = sess.run(conv_interface) tf_logging.info( "data_type: %r, use_gpu: %r, grouped_conv: %r, max diff = %f", data_type, use_gpu, grouped_conv, np.amax(np.absolute(native_result - interface_result))) self.assertArrayNear( np.ravel(native_result), np.ravel(interface_result), tolerance) self.assertShapeEqual(native_result, conv_native) self.assertShapeEqual(native_result, conv_interface) def testDepthwiseConv2D(self): for index, (input_size, filter_size, _, stride, padding) in enumerate(ConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2D, %dth config: %r * %r, stride: %d, padding: " "%s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: tf_logging.info("Testing without grouped_conv") self._VerifyValues( input_size, filter_size, stride, padding, data_type, use_gpu=True) tf_logging.info("Testing with grouped_conv") self._VerifyValues( input_size, filter_size, stride, padding, data_type, use_gpu=True, grouped_conv=True) def testDepthwiseConv2DWithUnknownShape(self): # GitHub issue 22110. if not test.is_gpu_available(): return with self.test_session(use_gpu=True): x = array_ops.placeholder(dtypes.float32) f = np.ones([1, 1, 1, 1], np.float32) v = nn_impl.depthwise_conv2d( x, f, [1, 1, 1, 1], "VALID", rate=[2, 1], data_format="NCHW") self.assertAllEqual( np.ones([1, 1, 1, 1], np.float32), v.eval(feed_dict={x: np.ones([1, 1, 1, 1], np.float32)})) def testDepthwiseConv2DFormat(self): if not test.is_gpu_available(): return for index, (input_size, filter_size, _, stride, padding) in enumerate(ConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DFormat, %dth config: %r * %r, stride: %d, " "padding: %s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: self._VerifyValues( input_size, filter_size, stride, padding, data_type, use_gpu=True, data_format="NCHW") # This is testing against hand calculated results. def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected, use_gpu): """Verifies the output values of the depthwise convolution function. Args: tensor_in_sizes: Input tensor dimensions in [batch, input_rows, input_cols, input_depth]. filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, input_depth, depth_multiplier]. stride: Stride. padding: Padding type. expected: An array containing the expected operation outputs. use_gpu: Whether to use GPU. """ total_size_1 = 1 total_size_2 = 1 for s in tensor_in_sizes: total_size_1 *= s for s in filter_in_sizes: total_size_2 *= s # Initializes the input tensor with array containing incrementing # numbers from 1. x1 = [f * 1.0 for f in range(1, total_size_1 + 1)] x2 = [f * 1.0 for f in range(1, total_size_2 + 1)] with self.test_session(use_gpu=use_gpu) as sess: t1 = constant_op.constant(x1, shape=tensor_in_sizes) t1.set_shape(tensor_in_sizes) t2 = constant_op.constant(x2, shape=filter_in_sizes) conv = nn_ops.depthwise_conv2d_native( t1, t2, strides=[1, stride, stride, 1], padding=padding) value = sess.run(conv) tf_logging.info("value = %r", value) self.assertArrayNear(expected, np.ravel(value), 1e-5) self.assertShapeEqual(value, conv) def testConv2D2x2Filter(self): # The inputs look like this (it's a 3 x 2 matrix, each of depth 2): # # [ (1.0, 2.0), (3.0, 4.0), ( 5.0, 6.0) ] # [ (7.0, 8.0), (9.0, 10.0), (11.0, 12.0) ] # We can view this as two inputs # # input depth 0: # # [ 1.0, 3.0, 5.0 ] # [ 7.0, 9.0, 11.0 ] # # input depth 1: # # [ 2.0, 4.0, 6.0 ] # [ 8.0, 10.0, 12.0 ] # # The filter looks like this (it has two 2 x 2 patches, each generating 2 # depths): # # filter #0: # # [ (1.0, 3.0), ( 5.0, 7.0)] # [ (9.0, 11.0), (13.0, 15.0)] # # filter #1: # # [ ( 2.0, 4.0), ( 6.0, 8.0)] # [ (10.0, 12.0), (14.0, 16.0)] # # So the outputs are: # # (position 0, 0: in_depth 0, output_depth 0 -- using filter #0) # 1.0 * 1.0 + 7.0 * 9.0 + 3.0 * 5.0 + 9.0 * 13.0 = 196 # (position 0, 0: in_depth 0, output_depth 1 -- using filter #1) # 1.0 * 2.0 + 7.0 * 10.0 + 3.0 * 6.0 + 9.0 * 14.0 = 216 # (position 0, 0: in_depth 1, output_depth 2 -- using filter #0) # 2.0 * 3.0 + 8.0 * 11.0 + 4.0 * 7.0 + 10.0 * 15.0 = 272 # (position 0, 0: in_depth 1, output_depth 3 -- using filter #1) # 2.0 * 4.0 + 8.0 * 12.0 + 4.0 * 8.0 + 10.0 * 16.0 = 296 # # (position 1, 0: in_depth 0, output_depth 0 -- using filter #0) # 3.0 * 1.0 + 9.0 * 9.0 + 5.0 * 5.0 + 11.0 * 13.0 = 252 # (position 1, 0: in_depth 0, output_depth 1 -- using filter #1) # 3.0 * 2.0 + 9.0 * 10.0 + 5.0 * 6.0 + 11.0 * 14.0 = 280 # (position 1, 0: in_depth 1, output_depth 2 -- using filter #0) # 4.0 * 3.0 + 10.0 * 11.0 + 6.0 * 7.0 + 12.0 * 15.0 = 344 # (position 1, 0: in_depth 1, output_depth 3 -- using filter #1) # 4.0 * 4.0 + 10.0 * 12.0 + 6.0 * 8.0 + 12.0 * 16.0 = 376 expected_output = [196, 216, 272, 296, 252, 280, 344, 376] self._VerifyHandValues( tensor_in_sizes=[1, 2, 3, 2], filter_in_sizes=[2, 2, 2, 2], stride=1, padding="VALID", expected=expected_output, use_gpu=False) self._VerifyHandValues( tensor_in_sizes=[1, 2, 3, 2], filter_in_sizes=[2, 2, 2, 2], stride=1, padding="VALID", expected=expected_output, use_gpu=True) # Gradient checkers. This tests depthwise gradient computations for both # BackpropFilter and BackpropInput by comparing gradients computed by the # depthwise gradient ops with the gradients computed numerically (details can # be found in the compute_gradient_error(). # Note this check is very expensive so the input should not be too big. def _ConstructAndTestGradient(self, input_shape, filter_shape, output_shape, stride, padding, data_type, test_input, use_gpu, grouped_conv=False, data_format="NHWC"): input_size = 1 for x in input_shape: input_size *= x filter_size = 1 for x in filter_shape: filter_size *= x input_data = [x * 1.0 / input_size for x in range(0, input_size)] filter_data = [x * 1.0 / filter_size for x in range(0, filter_size)] ops.reset_default_graph() graph = ops.get_default_graph() with self.session(graph=graph, use_gpu=use_gpu) as sess: tolerance = { dtypes.float16: 4e-0, dtypes.float32: 8e-4, dtypes.float64: 1e-12, }[data_type] input_tensor = constant_op.constant( input_data, shape=input_shape, dtype=data_type, name="input") filter_tensor = constant_op.constant( filter_data, shape=filter_shape, dtype=data_type, name="filter") native_input = input_tensor strides = [1, stride, stride, 1] if data_format == "NCHW": # Transpose from NHWC input to NCHW # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] native_input = array_ops.transpose(input_tensor, [0, 3, 1, 2]) input_shape = [ input_shape[0], input_shape[3], input_shape[1], input_shape[2] ] output_shape = [ output_shape[0], output_shape[3], output_shape[1], output_shape[2] ] strides = [1, 1, stride, stride] with sess.graph._kernel_label_map({ "DepthwiseConv2dNative": "cudnn_grouped_convolution", "DepthwiseConv2dNativeBackpropInput": "cudnn_grouped_convolution", "DepthwiseConv2dNativeBackpropFilter": "cudnn_grouped_convolution", } if grouped_conv else {}): depthwise_conv2d = nn_ops.depthwise_conv2d_native( native_input, filter_tensor, strides, padding, data_format=data_format, name="depthwise_conv2d") self.assertEqual(output_shape, depthwise_conv2d.get_shape()) try: if test_input: err = gradient_checker.compute_gradient_error( native_input, input_shape, depthwise_conv2d, output_shape) else: err = gradient_checker.compute_gradient_error( filter_tensor, filter_shape, depthwise_conv2d, output_shape) except errors.InvalidArgumentError as e: # Grouped convolution kernel is only registered for cuDNN 7. Silently # return when we are running on an earlier version or without GPU. if grouped_conv and e.message.startswith( "No OpKernel was registered to support Op 'DepthwiseConv2dNative'"): tf_logging.warn("Skipping grouped convolution test") return raise e tf_logging.info( "data_type: %r, use_gpu: %r, grouped_conv: %r, error = %f", data_type, use_gpu, grouped_conv, err) self.assertLess(err, tolerance) def testDepthwiseConv2DInputGrad(self): for index, (input_size, filter_size, output_size, stride, padding) in enumerate(CheckGradConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DInputGrad, %dth config: %r * %r, stride: %d, " "padding: %s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: self._ConstructAndTestGradient( input_size, filter_size, output_size, stride, padding, data_type, test_input=True, use_gpu=True) self._ConstructAndTestGradient( input_size, filter_size, output_size, stride, padding, data_type, test_input=True, use_gpu=True, grouped_conv=True) def testDepthwiseConv2DInputGradFormat(self): if not test.is_gpu_available(): return for index, (input_size, filter_size, output_size, stride, padding) in enumerate(CheckGradConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DInputGradFormat, %dth config: %r * %r, " "stride: %d, padding: %s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: self._ConstructAndTestGradient( input_size, filter_size, output_size, stride, padding, data_type, test_input=True, use_gpu=True, data_format="NCHW") def testDepthwiseConv2DFilterGrad(self): for index, (input_size, filter_size, output_size, stride, padding) in enumerate(CheckGradConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DFilterGrad, %dth config: %r * %r, stride: " "%d, padding: %s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: self._ConstructAndTestGradient( input_size, filter_size, output_size, stride, padding, data_type, test_input=False, use_gpu=True) def testDepthwiseConv2DFilterGradFormat(self): if not test.is_gpu_available(): return for index, (input_size, filter_size, output_size, stride, padding) in enumerate(CheckGradConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DFilterGradFormat, %dth config: %r * %r, " "stride: %d, padding: %s", index, input_size, filter_size, stride, padding) for data_type in [dtypes.float32, dtypes.float64]: self._ConstructAndTestGradient( input_size, filter_size, output_size, stride, padding, data_type, test_input=False, use_gpu=True, data_format="NCHW") def _CompareBackpropInputFloat(self, input_sizes, filter_sizes, output_sizes, stride, padding): x1 = np.random.rand(*filter_sizes).astype(np.float32) x2 = np.random.rand(*output_sizes).astype(np.float32) def _GetVal(use_gpu): with self.test_session(use_gpu=use_gpu): t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) t1 = constant_op.constant(x1, shape=filter_sizes) t2 = constant_op.constant(x2, shape=output_sizes) backprop = nn_ops.depthwise_conv2d_native_backprop_input( t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) ret = backprop.eval() self.assertShapeEqual(ret, backprop) return ret gpu_value = _GetVal(use_gpu=True) cpu_value = _GetVal(use_gpu=False) self.assertAllClose(cpu_value, gpu_value, rtol=1e-4, atol=1e-4) def _CompareBackpropInputDouble(self, input_sizes, filter_sizes, output_sizes, stride, padding): x1 = np.random.rand(*filter_sizes).astype(np.float64) x2 = np.random.rand(*output_sizes).astype(np.float64) def _GetVal(use_gpu): with self.test_session(use_gpu=use_gpu): t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) t1 = constant_op.constant(x1, shape=filter_sizes) t2 = constant_op.constant(x2, shape=output_sizes) backprop = nn_ops.depthwise_conv2d_native_backprop_input( t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) ret = backprop.eval() self.assertShapeEqual(ret, backprop) return ret gpu_value = _GetVal(use_gpu=True) cpu_value = _GetVal(use_gpu=False) self.assertAllClose(cpu_value, gpu_value, rtol=1e-4, atol=1e-4) def testDepthwiseConv2DInputGradCompare(self): for index, (input_size, filter_size, output_size, stride, padding) in enumerate(ConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DInputGradCompare, %dth config: %r * %r, " "stride: %d, padding: %s", index, input_size, filter_size, stride, padding) self._CompareBackpropInputFloat(input_size, filter_size, output_size, stride, padding) self._CompareBackpropInputDouble(input_size, filter_size, output_size, stride, padding) def _CompareBackpropFilterFloat(self, input_sizes, filter_sizes, output_sizes, stride, padding): x0 = np.random.rand(*input_sizes).astype(np.float32) x2 = np.random.rand(*output_sizes).astype(np.float32) def _GetVal(use_gpu): with self.test_session(use_gpu=use_gpu): t0 = constant_op.constant(x0, shape=input_sizes) t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) t2 = constant_op.constant(x2, shape=output_sizes) backprop = nn_ops.depthwise_conv2d_native_backprop_filter( t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) ret = backprop.eval() self.assertShapeEqual(ret, backprop) return ret gpu_value = _GetVal(use_gpu=True) cpu_value = _GetVal(use_gpu=False) self.assertAllClose(cpu_value, gpu_value, rtol=1e-4, atol=1e-4) def _CompareBackpropFilterDouble(self, input_sizes, filter_sizes, output_sizes, stride, padding): x0 = np.random.rand(*input_sizes).astype(np.float64) x2 = np.random.rand(*output_sizes).astype(np.float64) def _GetVal(use_gpu): with self.test_session(use_gpu=use_gpu): t0 = constant_op.constant(x0, shape=input_sizes) t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) t2 = constant_op.constant(x2, shape=output_sizes) backprop = nn_ops.depthwise_conv2d_native_backprop_filter( t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) ret = backprop.eval() self.assertShapeEqual(ret, backprop) return ret gpu_value = _GetVal(use_gpu=True) cpu_value = _GetVal(use_gpu=False) self.assertAllClose(cpu_value, gpu_value, rtol=1e-4, atol=1e-4) def testDepthwiseConv2DFilterGradCompare(self): for index, (input_size, filter_size, output_size, stride, padding) in enumerate(ConfigsToTest()): tf_logging.info( "Testing DepthwiseConv2DFilterGradCompare, %dth config: %r * %r, " "stride: %d, padding: %s", index, input_size, filter_size, stride, padding) self._CompareBackpropFilterFloat(input_size, filter_size, output_size, stride, padding) self._CompareBackpropFilterDouble(input_size, filter_size, output_size, stride, padding) if __name__ == "__main__": test.main()
{ "task_name": "lcc" }
Passage 1: Mark Wallwork Mark Andrew Wallwork( born 14 December 1960) is a former English cricketer active from 1980 to 1982 who played for Lancashire. He was born in Urmston, Lancashire. He appeared in one first- class match as a righthanded batsman and wicketkeeper. He scored no runs and held three catches. Passage 2: Daniel Franco Daniel Franco( born November 11, 1971 in Los Angeles, California) is an American fashion designer. He achieved notability for appearing in three seasons of" Project Runway". He is also known for achieving the same place( 12th) 3 times. Passage 3: Alfred Oppenheim (chemist) Alfred Oppenheim( 3 November 1878 in Berlin – 14 May 1943 at the same place) was a German chemist and gas mantle manufacturer. Passage 4: Hieronymus Payer Hieronymus Payer( 13 February 1787 in Vienna- Meidling; died 17 August 1845 in the same place) was an Austrian composer and pianist. Passage 5: James Rewcastle James Rewcastle( c.1802–1867) was the first secretary of the Newcastle Temperance movement, and a songwriter born in the Newcastle area. His most well- known song is possibly “ Jackey and Jenny ”. Passage 6: Jenny Wallwork Jennifer" Jenny" Wallwork( born 17 January 1987 in Bolton) is an English badminton player who has achieved international success in both the women's events and the mixed doubles event, including a Commonwealth Silver medal in 2010. She represented her country 42 times, being the highest ranking female player for 4 years. She won the mixed doubles Bulgarian International in 2004, the Scottish Open in 2005, and the Dutch Open in 2006. She won the Swedish International mixed doubles in 2012. She won the women's doubles at the Irish International in 2005. Her mother, Jill played badminton for England, and her father, Brian is a coach for the sport. In 2011 Jenny won both the mixed and women's doubles at the English National Championships but 2013 she quit professional badminton after saying she was undervalued and ignored by the governing body Badminton England. Passage 7: James Wallwork James Harold Wallwork( born September 17, 1930 in Belleville, New Jersey) is an American Republican Party politician who served in both houses of the New Jersey Legislature and twice sought the Republican nomination for Governor. Passage 8: Ron Wallwork Ronald Edward Wallwork( born 26 May 1941) is a retired male race walker from England, who represented his home nation at two Commonwealth Games. Passage 9: C. P. Rajendran Chittenipattu Puthenveettil Rajendran, also known among his peers as CP( born 29 May 1955, Ottapalam, Palakkad Kerala India) is an Indian geologist who has worked mainly in paleoseismology and Indian geology. Passage 10: Peter Dirck Keyser Peter Dirck Keyser( born in Philadelphia, Pennsylvania, 8 February 1835; died same place, 8 March 1897) was a United States ophthalmologist. Question: Were both C. P. Rajendran and Jenny Wallwork, born in the same place? Answer: no
{ "task_name": "2WikiMultihopQA" }
import sys sys.path.append("/Users/pascal/GDrive/sky_package/sky/") from utils import * from training import * from findLeaf import * from bs4 import BeautifulSoup def uniqifyOverTraining(list_of_lists): uniques = [] for x in list_of_lists[0]: if all([bool(x in y) for y in list_of_lists]): uniques.append(x) return uniques def findParentIdentifiers(x, soup, nLevel=3): parents = [] try: for parent_attrs in [parent.attrs for parent in x.parents][:nLevel]: if len(soup.findAll(**{"attrs" : parent_attrs})) == 1: parents.append({"attrs" : parent_attrs}) for parent_attrs in [{"name" : parent.name} for parent in x.parents][:nLevel]: if len(soup.findAll(**{"name" : parent.name})) == 1: parents.append({"name" : parent.name}) except: pass return parents def findSharedKeyValues(training, trainingLeafs): case_options = [] for soup, case in zip(training.soups, trainingLeafs): options = [] for leaf in case: options.extend(findParentIdentifiers(leaf, soup)) options.extend(findByTag(leaf, soup)) case_options.append(options) shared_options = [] for option in case_options[0]: if all([bool(option in case) for case in case_options]): shared_options.append(option) return shared_options def findByTag(node, soup, nLevel=5): goodTags = [] tags = [] tags.extend([x.name for x in node.parents][:nLevel]) try: tags.append(node.name) except: pass for tag in tags: if len(soup.findAll(tag)) == 1: goodTags.append({"name" : tag}) return goodTags def secondLevelDown(soup, outcome, unique_keys): solution = [] num = 0 for unique_key in unique_keys: num += 1 #attempt = soup #for key in unique_key: ik denk dat ik hier bedoedle dat ik ook halve matches kan doen attempt = soup.find(**unique_key) if attempt.text == outcome: solution.append([unique_key, BeautifulSoup.get_text]) if stripReasonableWhite(attempt.text) == stripReasonableWhite(outcome): solution.append([unique_key, BeautifulSoup.get_text, stripReasonableWhite]) splitting = splitN(attempt.text, outcome) if splitting: for splitable in splitting: solution.append([unique_key, BeautifulSoup.get_text, splitSolution(splitable)]) return solution def stripReasonableWhite(x): return re.sub(r"\s+", " ", x).strip() def splitN(txt, outcome): # consider splitting to get result txt = stripReasonableWhite(txt) outcome = stripReasonableWhite(outcome) splitables = set(txt.replace(outcome, '', 1)) - set(' ') options = set() for s in splitables: for i, x in enumerate(txt.split(s)): if stripReasonableWhite(x) == stripReasonableWhite(outcome): options.add((s, i)) return options def splitSolution(how): def solution(txt): return txt.split(how[0])[how[1]] return solution def asNumeric(x): return re.sub("[^0-9]", "", x) def applySolutionChain(solution, x): for sol in solution: if isinstance(sol, dict): x = x.find(**sol) else: x = sol(x) return x def buildSolution(training): res = findLeaf(training) print("len(res)", len(res)) x = findSharedKeyValues(training, res) print("len(shared)", len(x)) solutions = secondLevelDown(training.soups[0], training.targets[0], x) print("len(solutions)", len(solutions)) return solutions def testAutoScraperSolutions(autoScraper, training, verbose = False): num = 0 any_succes = False for solution in autoScraper: num += 1 if all([applySolutionChain(solution, soup) == target for soup, target in zip(training.soups, training.targets)]): result = "SUCCESFULL" any_succes = True else: result = "UNSUCCESFULL" if verbose: print("Scraper method: ", num, " was ", result) return any_succes def tryUniqueID(c, sp): return len(sp.findAll(c.name, attrs=c.attrs)) == 1 def buildNewSolution(tr): childs = [] num = 0 options = [] for soup, target in zip(tr.soups, tr.targets): print('num',num) num+=1 for c in soup.findChildren(): try: if c.name not in ['body', 'html']: if target in c.text: childs.append([c, len(c.text)]) except: pass tmp = [] for i,x in enumerate(childs[::-1]): if tryUniqueID(x[0], soup): attrs = x[0].attrs attrs['name'] = x[0].name attrs = {'attrs' : attrs} if x[0].text == target: tmp.append((attrs, BeautifulSoup.get_text)) elif stripReasonableWhite(x[0].text) == stripReasonableWhite(target): tmp.append((attrs, BeautifulSoup.get_text, stripReasonableWhite)) elif splitN(x[0].text, target): for splitable in splitN(x[0].text, target): tmp.append((attrs, BeautifulSoup.get_text, splitSolution(splitable))) else: print(len([y for y in x[0].children])) else: print('not unique', len([y for y in x[0].children])) options.append(tmp) good_options = [] if options: for x in options[0]: if all(x in y for y in options[1:]): good_options.append(x) return good_options #testAutoScraperSolutions(buildSolution(tr), tr, False) # tr1 = Training("marktplaats-testcase1", "/Users/pascal/GDrive/sky_package/sky/tests/").load() # tr2 = Training("nieuwsdumper-testcase1", "/Users/pascal/GDrive/sky_package/sky/tests/").load() # tr3 = Training("nieuwsdumper-testcase2", "/Users/pascal/GDrive/sky_package/sky/tests/").load() # tr4 = Training("bouwmaterieel-testcase1", "/Users/pascal/GDrive/sky_package/sky/tests/").load() # tr5 = Training("marktplaats-testcase2", "/Users/pascal/GDrive/sky/sky/tests/") # tr5.addLinks(["http://www.marktplaats.nl/a/telecommunicatie/mobiele-telefoons-samsung/m861980349-hdc-galaxy-s5-nieuw-in-doos.html?c=a2384ef0ece270f44503df9f8598c624&previousPage=lr", # "http://www.marktplaats.nl/a/telecommunicatie/mobiele-telefoons-samsung/m862001039-samsung-galaxy-s3-neo.html?c=a2384ef0ece270f44503df9f8598c624&previousPage=lr", "http://www.marktplaats.nl/a/telecommunicatie/mobiele-telefoons-toebehoren-en-onderdelen/m862001036-iphone-3-4-4s-usb-oplaad-snoer.html?c=a2384ef0ece270f44503df9f8598c624&previousPage=lr"]) # tr5.viewAll() # tr6 = Training("pypi-author", "/Users/pascal/GDrive/sky_package/sky/tests/").load() # links = ["http://www.forbes.com/sites/rogerkay/2014/11/10/sparkcognition-meets-ibms-watson-starts-conversation/"] # import justext # url = "http://www.forbes.com/sites/rogerkay/2014/11/10/sparkcognition-meets-ibms-watson-starts-conversation/" # html = urllib.urlopen(url).read() # paragraphs = justext.justext(html, justext.get_stoplist('English')) # title = "SparkCognition Meets IBM's Watson, Starts Conversation" # res = [] # for x in paragraphs: # if not x.is_boilerplate: # res.append(x.text) # newres = [] # for x in res[res.index(title)+1:]: # newres.append(x) # for x in newres: # print(x.encode("ascii", "ignore")) # res = findLeaf(tr3) # x = findSharedKeyValues(tr3, res) # secondLevelDown(tr3.soups[0], tr3.targets[0], x) tr1 = Training("marktplaats-testcase1", "/Users/pascal/GDrive/sky_package/sky/tests/").load() from collections import Counter class SoupStats(): def __init__(self, soup): self.soup = soup self.counter = Counter() for child in soup.findChildren(): for atts in child.attrs.items(): k,v = atts self.counter[atts] += 1 self.counter[k] += 1 self.counter[v] += 1 z = SoupStats(soup) counter = Counter() for child in soup.findChildren(): for atts in child.attrs.items(): k,v = atts counter[k] += 1 if isinstance(v, list): for l in v: counter[(k, l)] += 1 counter[l] += 1 counter[(k, " ".join(v))] += 1 else: counter[atts] += 1 counter[v] += 1 r import lxml.html lxml.html.tostring() html = 'html' tree = lxml.html.fromstring(html) tree.findall('.//*') from lxml.html import HtmlComment # or similar no_comments=[element for element in tree if not isinstance(element, HtmlComment)] tr = Training('betterdoctor-doctor-referalls', '/Users/pascal/GDrive/sky_package/sky/tests/').load()
{ "task_name": "lcc" }
Passage 1: West Oaks West Oaks is a neighborhood in Minot, North Dakota. The neighborhood is bounded by Oak Park to the North, the Souris River to the east, the Soo Line Railroad tracks to the south and Sixteenth Street SW. The neighborhood is home to the West Oaks Animal Hospital, the West Oaks Apartments, Harleys Automotive Center and gas station, Eagles Wings Community Fellowship and a number of single family homes. Oak Park's south entrance is located in the neighborhood on Oak Drive SW. A thin strip of land between the Oak Park Oxbow and the Souris River connects the park with the neighborhood. The neighborhood was greatly impacted by the Souris River flood in 2011. In June 2011, the Washington Post printed a story about the Minot flood on the front page with an accompanying photograph of Harleys and the nearby Arrowhead Mall. Water inundated both structures, despite the large dikes constructed around both buildings. On June 26, 2011, the New York Times also printed an article with an aerial photograph of the flooded Harleys. Similar aerial photographs of the flood at that location are displayed at the Harleys gas station. Passage 2: AMC Theatres AMC Theatres (originally an abbreviation for American Multi-Cinema, often referred to simply as AMC and known in some countries as AMC Cinemas) is an American movie theater chain owned and operated by AMC Entertainment Inc., which is itself owned by AMC Entertainment Holdings, Inc., majority-owned by Chinese conglomerate Dalian Wanda Group. Founded in 1920, AMC has the largest share of the American theater market ahead of Regal Entertainment Group and Cinemark Theatres. The chain has 86 locations in mainland China, home of the Dalian Wanda Group. The company's headquarters are located in Leawood, Kansas. Passage 3: Litchfield Theatres The company began as a subsidiary of The Litchfield Company in the 1960s, and was founded by A. Foster McKissick in the Southeastern U.S.. The theatre chain, however, did not last very long before Mr. McKissick had to sell the company in the late 1960s. The theatre chain was born again in 1976 when it was again operating in the Southeastern United States as Litchfield Theatres. This time the company lasted until the late 1980s when Mr. McKissick was forced to sell not only the theatre chain, but also its parent company, The Litchfield Company. The theatre chain was sold to United Artists Theaters (which itself was sold to Regal Entertainment Group in 1999), and The Litchfield Company was sold to a real estate group in Pawley's Island South Carolina. The Litchfield Company has continued to exist, but the theatre chain has not been revived. Passage 4: Landmark Cinemas Landmark Cinemas, Inc. is a movie theatre chain that operates 45 theatres across the four western provinces of Canada and in Ontario. The chain was founded in 1965. The company's corporate office is located in Calgary, Alberta. Passage 5: Kentucky Oaks Mall Kentucky Oaks Mall is an enclosed super-regional shopping mall in Paducah, Kentucky, USA. Managed by Cafaro Company, the mall includes more than 90 inline stores, as well as regional radio station Rock 98.3 WJLI. Its anchor stores comprise JCPenney, Best Buy, Elder-Beerman, a Dillard's store divided into two sub-stores, and Dick's Sporting Goods. It was the largest mall in Kentucky by gross leasable area when it opened, and remains the state's third-largest, behind Fayette Mall in Lexington and Mall St. Matthews in Louisville. Passage 6: Cinemark Theatres Cinemark USA, Inc. is an American movie theatre chain owned by Cinemark Holdings, Inc. operating throughout the Americas and in Taiwan. It is headquartered in Plano, Texas in the Dallas-Fort Worth area. It is the largest movie theatre chain in Brazil, with a 30% market share. Passage 7: CineVista Theatres CineVista Theatres was a movie theatre chain in Puerto Rico founded in 1997. As CineVista continued to close all of the theaters, it was bankrupt. After CineVista was bankrupt, Caribbean Cinemas is the only theatre chain in Puerto Rico. Passage 8: Ciné de Chef Ciné de Chef is a combined luxury movie theatre and gourmet restaurant, located in Apgujeong, southern Seoul. It is operated by CJ CGV, South Korea's largest multiplex movie theatre chain, and opened on 3 May 2007, drawing over 2000 viewers in its first few months. Passage 9: West Oaks Mall (Orlando) West Oaks Mall is a mall located in Ocoee, Florida near Orlando. It has 115 store spaces, a food court, and a 14-screen AMC theater. Passage 10: Shaw Organisation Shaw Organisation is a film distribution company and movie theatre chain founded by brothers Runme Shaw and Run Run Shaw who went to Singapore in the 1920s to expand their family business founded by Runje Shaw. The company originally operated as a distributor for the Shaw brothers' Tianyi Film Company (also called Unique) in Shanghai. Run Run Shaw later moved to Hong Kong in the 1950s to run Shaw Brothers Studio, whilst Runme Shaw stayed in Singapore to continue Shaw Organisation's operations. Unlike Tianyi, Shaw Organisation does not produce films but distribute them in their theatres. Question: West Oaks Mall includes a theatre by the movie theatre chain founded in what year? Answer: 1920
{ "task_name": "hotpotqa" }
Passage 1: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Passage 2: Raid on Entebbe (film) Raid on Entebbe is a 1977 NBC television film directed by Irvin Kershner. It is based on an actual event: Operation Entebbe and the freeing of hostages at Entebbe Airport in Entebbe, Uganda, on July 4, 1976. The portrayal of Prime Minister Yitzhak Rabin was Peter Finch's final performance; he died five days after the film's release. "Raid on Entebbe" focuses on the basic facts of the rescue of hostages held in Uganda. The film recounts the events and response of the Israeli government along with the controversy that the rescue stirred. A similar production on the Entebbe raid, "Victory at Entebbe" was rushed through production by ABC and broadcast one month earlier in December 1976. Passage 3: Irvin Kershner Irvin Kershner (born Isadore Kershner; April 29, 1923November 27, 2010) was an American director, actor, and producer of film and television. He gained notice early in his career as a filmmaker for directing quirky, independent drama films, while working as an influential lecturer at the University of Southern California. Later in his career, he transitioned to high-budget blockbusters such as "The Empire Strikes Back", the James Bond adaptation "Never Say Never Again", and "RoboCop 2". Through the course of his career, he received numerous accolades, and was nominated for both a Primetime Emmy Award and a Palme d'Or. Passage 4: Amit Bimrot Amit Bimrot is an Indian actor who is best known for his role in super hit film" Raid" and Netflix web series" Bard of Blood". Passage 5: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 6: Harri Nykänen Harri Kalervo Nykänen( born 1953) is a Finnish crime writer. The film Raid is based on his work. Passage 7: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 8: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 9: William Manger William Manger is an American sound editor. He was nominated at the 62nd Academy Awards for the film" Black Rain". This was in the category of Best Sound Editing. He shared his nomination with Milton Burrow. He won one BAFTA award for sound for the film" War Games". As well as an Emmy Award for the TV film" Raid on Entebbe". He has 3 other Emmy nominations also. Passage 10: Peter Levin Peter Levin is an American director of film, television and theatre. Question: Which country the director of film Raid On Entebbe (Film) is from? Answer: American
{ "task_name": "2WikiMultihopQA" }
Document: One of two injured mothers in Monday's deadly crash in Brooklyn that claimed the lives of the women's two young children is a Tony-winning actress who also appeared in the TV show "The Americans," a police source familiar with the investigation told NBC 4 New York. Lori Bordonaro reports. (Published Wednesday, March 7, 2018) What to Know Dorothy Bruns, 44, was found dead in her NYC home sometime Tuesday afternoon of an apparent suicide, a senior law enforcement official said Broadway star Ruthie Ann Miles was injured in the Brooklyn crash along with her friend; both of their young children were killed Miles, who was expecting a baby girl with her husband Jonathan Blumenstein, lost the unborn baby due to injuries from the March crash The woman charged in the Brooklyn crash that killed Broadway star Ruthie Ann Miles' young daughter and unborn child has died of an apparent suicide, a senior law enforcement official briefed on the case tells NBC 4 New York. Dorothy Bruns, 44, was found dead in her Staten Island home Tuesday afternoon, the senior law enforcement official said. Authorities say pills and a note were found nearby. Miles was walking with her friend and their two young children in Park Slope on March 5 when Bruns allegedly blew through a red light and plowed into the group, killing both children — Miles’ daughter, Abigail, and the friend's 1-year-old son, Joshua. All four were found on the pavement with various injuries. Miles' unborn daughter initially survived the crash, but the actress miscarried a month before she was due. The loss was related to injuries from the crash. Bruns was eventually indicted in connection with the case; she was arrested at her Staten Island home May 3 on a 10-count indictment charging her with manslaughter, criminally negligent homicide, assault and other crimes. She had faced 15 years in jail. Bruns told police at the time she had medical issues — and though her license had been suspended she had not been criminally charged in the case until about two months after the crash. Prosecutors said she had suffered a seizure at the time of the collision, and had been driving in direct defiance of a doctor's orders following a hospitalization less than eight weeks prior. That hospitalization stemmed from yet another car crash — that time into a parked vehicle. Police are investigating Bruns' death, the senior law enforcement official said. ||||| NEW YORK (CBSNewYork) – The woman police say drove her car through a Brooklyn crosswalk and killed a 1-year-old and 4-year-old child, leaving several others injured, has been found dead in her Staten Island home. Dorothy Bruns, 44, of Staten Island, told investigators she suffered multiple sclerosis and had a seizure before running the red light on March 5. Police were called to her Staten Island address for a wellness check after a friend said she had not heard from her. Officers found Bruns’ body and evidence she had ingested pills, and she was pronounced dead at the scene. A note found near body made reference to “I don’t want to live like this anymore.” Earlier this year, Bruns had been indicted by a grand jury on charges of manslaughter, criminally negligent homicide and assault. Police said she was driving her sedan westbound on Park Slope’s 9th Street near 5th Avenue when her vehicle struck a group of pedestrians, including a pair of mothers – each with a child in a stroller. Killed were 1-year-old Joshua Lew and 4-year-old Abigail Blumenstein. The girl’s mother is Tony Award-winning actress Ruthie Ann Miles. In the past, medics had been dispatched to Bruns’ home numerous times following 911 calls that she needed emergency medical help. A background check of her driving shows she had about a dozen traffic violations against her since 2016, including speeding and running red lights. Prosecutors said a doctor told Bruns more than once not to drive. ||||| The woman whose car struck and killed two children, including the daughter of Broadway star Ruthie Ann Miles, has been found dead. A friend checked on Dorothy Bruns, 44, after not hearing from her, an New York City Police Department rep tells PEOPLE. When police arrived, Bruns was unconscious and unresponsive in a bedroom with no obvious signs of trauma. She was pronounced dead on the scene by emergency medical responders. Get push notifications with news, features and more. Bruns died at her Staten Island residence by an apparent suicide, a second NYPD spokesperson tells PEOPLE. She died of an overdose, according to a third police source, and a note was found “expressing [her] desire to no longer live.” In March, Bruns allegedly hit and killed two pedestrians in Brooklyn: Miles’ 4-year-old Abigail Blumenstein and a 1-year-old named Joshua Lew. Miles, who was seven months pregnant, and Lew’s mother Lauren, a friend of Miles, were injured. RELATED: Husband of Pregnant Woman Killed in Car Crash Shares Photos of Wife and Unborn Child in Coffin Two months later, Miles’ family lawyer Ben Rubinowitz announced that Miles and her husband Jonathan Blumenstein had lost the baby they were expecting. They had named the child Sophia Rosemary Wong Blumenstein. Dorothy Bruns at the scene of the accident Todd Maisel/NY Daily News/Getty Earlier in May, a Brooklyn grand jury indicted Bruns. She was arraigned on charges of manslaughter, criminally negligent homicide and assault, a prosecution source told PEOPLE at the time. The police source says that Bruns had only posted bail in the case last month. Police sources previously told PEOPLE that Bruns claimed she experienced a seizure at the time of the March crash. Sources alleged that after running the red light, Bruns crashed into parked cars and dragged Lew’s stroller halfway down the street while the baby was in it. She had previously been ticketed for driving through red lights. RELATED VIDEO: Broadway Star Ruthie Ann Miles Loses Unborn Baby 2 Months After Daughter was Killed in Car Crash “Abigail was excited to be a big sister,” a source told PEOPLE in March. “She was the brightest little spirit. Every time you were around her, your heart couldn’t help but shine. She had the sweetest laugh and the loveliest personality. She was very much like her mother.” “Ruthie was a wonderful mother. She always put Abigail first and was really dedicated to spending time together,” the source continued. “The two had a very tight bond. They were inseparable.” Ruthie Ann Miles Paul Kolnik RELATED: Ruthie Ann Miles Is ‘Crushed’ After Losing Unborn Baby 2 Months After Daughter Was Killed In August, Miles returned to the stage for the first time since the tragedy in the revival of The King and I, reprising the performance that won her a Tony Award in 2015. “She is singing like an angel and commanding the stage with a heavenly force,” her costar Kelli O’Hara wrote on Twitter. “An inspiration to all. I knew you would want to know.” Summary: – The woman charged with hitting and killing two young children in a Brooklyn crosswalk in March was found dead Tuesday in an apparent suicide, NBC New York reports. Dorothy Bruns, 44, was charged in May with crimes including manslaughter, criminally negligent homicide, and assault and was facing 15 years behind bars. A friend went to check on Bruns after not hearing from her, and police ultimately responded to her Staten Island home and found her unresponsive, People reports. Pills and a suicide note were found nearby. CBS New York reports the note said something to the effect of, "I don't want to live like this anymore." Bruns, who had a number of driving citations and accidents in her past, had been explicitly instructed by a doctor not to drive due to medical issues when she allegedly ran a red light and hit a group of pedestrians, including pregnant Broadway star Ruthie Ann Miles, her friend, and their children. Bruns said she had a seizure that caused the accident. Both children—Abigail Blumenstein, 4, and Joshua Lew, 20 months—were killed, and Miles ended up losing her unborn baby just before her due date due to injuries suffered in the crash. Miles returned to the stage for the first time after the crash in August, reprising her role in The King and I for which she won a Tony in 2015. (The driver who hit and killed three siblings as they crossed to their school bus says she didn't realize it was a bus.)
{ "task_name": "multi_news" }
Document: has just been released from an Indiana jail ... TMZ has learned.Portwood walked out of the jail with a woman who appears to be her mother.Portwood was locked up yesterday -- when she was arrested and charged with felony domestic battery for allegedly beating up her baby daddy in front of their daughter.According to the police report filed with the court, Amber acknowledged that her violence was true anger and not staged for the TV show.One of the officers notes in the report that there were "multiple violent and physical fights between [Amber and Gary]" in which Amber punched, slapped and kicked him.In the outtakes that were not aired on theshow, the baby is clearly in the room watching the violence, according to the police report.Portwood has since pled not guilty to the charges. ||||| 'Teen Mom' Star Amber Portwood Caught Drinking? Email This 'Teen Mom' mother Amber Portwood has been in hot water lately -- specifically for The pictures, obtained by 'Teen Mom' mother Amber Portwood has been in hot water lately -- specifically for allegedly abusing her ex-fiance, Gary Shirley -- but new photos of the underage Portwood could cause her even more problems.The pictures, obtained by Life & Style , show what appears to be the MTV personality drinking from a bottle of vodka at a party in her hometown of Anderson, Ind. Filed under: TV News According to eyewitnesses, it didn't stop with alcohol. "She pulled out a bottle of pills," a source said."She said she needs to watch how much she drinks because she's on something," the source added.Portwood recently lost custody of her daughter Leah, but many believe she's not doing much about it. "Frankly, it doesn't look like Amber's in any hurry to get Leah back," an insider explained.Life & Style also reports that Amber is seeing multiple men, including Clint Yunker, a professional mixed martial arts fighter.For more on Amber, pick up this week's issue of Life & Style, on newsstands now. Summary: – Teen Mom star Amber Portwood has pleaded not guilty to beating baby daddy Gary Shirley. The altercation that was captured by MTV during the filming of the reality program shows Portwood slapping and hitting her then-boyfriend during a heated argument. All of it took place in front of the couple's 2-year-old daughter, Leah. Portwood, who faces felony charges of battery and child neglect, has been released from jail but can't yet have contact with her daughter, reports TMZ. Click here for a sample of Portwood's previous trouble.
{ "task_name": "multi_news" }
Passage 1: Andrew Chadwick Andrew Chadwick is a British political communication researcher. His work focuses on the fields of political communication and mobilisation, news and journalism, and democratic engagement and governance. He is Professor of Political Communication at Loughborough University, where he is also director of the Online Civic Culture Centre( O3C). His latest book" The Hybrid Media System: Politics and Power" was released in 2013 and in a second edition in 2017. Passage 2: Canadian Forum The Canadian Forum was a left- wing literary, cultural and political publication and Canada's longest running continually published political magazine( 1920 – 2000). Passage 3: Pink Pages Pink Pages was an Indian LGBT magazine that published online and print issues from 2009 to 2017. Passage 4: Sky Dayton Sky Dylan Dayton( born August 8, 1971) is an American entrepreneur and investor. He is the founder of Internet service provider EarthLink, co-founder of eCompanies, and the founder of Boingo. Passage 5: Lynda Lee Kaid Lynda Lee Kaid( August22, 1948 April13, 2011) was a Professor of Telecommunication and Research Foundation Professor in the College of Journalism& Communications at the University of Florida and named by" Communication Quarterly" as one of the most productive scholars in the communication discipline. She authored more than 30 books and more than 200 peer reviewed articles and chapters on political communication and political advertising. Kaid was honored as a Distinguished Alumni in 2007 from Southern Illinois University. She earned a doctorate and master's degree in speech communication and a bachelor's degree in German from SIU. She was a three- time Fulbright Scholar. The National Communication Association's Political Communication Division established the annual Lynda Lee Kaid Outstanding Dissertation in Political Communication award. The International Communication Association's Political Communication Division established the Keith R. Sanders and Lynda Lee Kaid Best Political Communication Article of the Year Award. Passage 6: Web enhancement A web enhancement is a bonus expansion to a role- playing game product, that can be read and/ or downloaded from the website of the company that published the role- playing product it is associated with. Passage 7: Routledge Routledge is a British multinational publisher. It was founded in 1836 by George Routledge, and specialises in providing academic books, journals and online resources in the fields of humanities, behavioural science, education, law and social science. The company publishes approximately 1,800 journals and 5,000 new books each year and their backlist encompasses over 70,000 titles. Routledge is claimed to be the largest global academic publisher within humanities and social sciences. In 1998, Routledge became a subdivision and imprint of its former rival, Taylor & Francis Group (T&F), as a result of a £90-million acquisition deal from Cinven, a venture capital group which had purchased it two years previously for £25 million. Following the merger of Informa and T&F in 2004, Routledge become a publishing unit and major imprint within the Informa 'academic publishing' division. Routledge is headquartered in the main T&F office in Milton Park, Abingdon, Oxfordshire and also operates from T&F offices globally including in Philadelphia, Melbourne, New Delhi, Singapore and Beijing. Passage 8: Political Communication (journal) Political Communication is a quarterly peer-reviewed academic journal covering political communication. It was established in 1980 and is published by Routledge on behalf of the American Political Science Association and the International Communication Association. The editor-in-chief is Claes de Vreese (University of Amsterdam). According to the "Journal Citation Reports", the journal has a 2018 impact factor of 4.339. Passage 9: Cyrus Massoumi Cyrus Massoumi is the founder of the investment fund humbition. He is also the founder of Zocdoc and was the company CEO for eight years. Passage 10: Chappell & Co. Chappell& Co. was an English company that published music and manufactured pianos. Question: Who is the founder of the company which published Political Communication (Journal)? Answer: George Routledge
{ "task_name": "2WikiMultihopQA" }
Passage 1: Michael Fassbender Michael Fassbender (born 2 April 1977) is an Irish actor. His feature film debut was in the fantasy war epic "300" (2007) as a Spartan warrior; his earlier roles included various stage productions, as well as starring roles on television such as in the HBO miniseries "Band of Brothers" (2001) and the Sky One fantasy drama "Hex" (2004–05). He first came to prominence for his role as IRA activist Bobby Sands in "Hunger" (2008), for which he won a British Independent Film Award. Subsequent roles include in the independent film "Fish Tank" (2009), as a Royal Marines lieutenant in "Inglourious Basterds" (2009), as Edward Rochester in the 2011 film adaptation of "Jane Eyre", as Carl Jung in "A Dangerous Method" (2011), as the sentient android David 8 in "Prometheus" (2012) and its sequel, "" (2017), and in the musical comedy-drama "Frank" (2014) as an eccentric musician loosely inspired by Frank Sidebottom. Passage 2: Michael Devine (hunger striker) Michael James "Mickey" Devine (26 May 1954–20 August 1981) was an Irish founding member of the Irish National Liberation Army (INLA). He died in prison during the 1981 Irish hunger strike. Passage 3: Michael Fassbender filmography Michael Fassbender is a German-Irish actor who made his screen debut in the 2001 war drama miniseries "Band of Brothers" as Sgt. Burton "Pat" Christenson. Fassbender followed this with a number of television roles including a German motorcycle courier in the drama "Hearts and Bones" (2001), Guy Fawkes in the miniseries "Gunpowder, Treason & Plot" (2004), Lt. Harry Colebourn in the film "A Bear Named Winnie" (2004), and Azazeal in the series "Hex" (2004–05). He made his film debut playing a Spartan soldier in Zack Snyder's "300" (2007). The following year Fassbender portrayed Irish republican Bobby Sands during the events of the 1981 Irish hunger strike in Steve McQueen's historical drama "Hunger". His performance garnered him the Best Actor award at the British Independent Film Awards, and the Irish Film and Television Awards. Passage 4: Francis Hughes Francis Hughes (28 February 1956 – 12 May 1981) was a volunteer in the Provisional Irish Republican Army (IRA) from Bellaghy, County Londonderry, Northern Ireland. Hughes was the most wanted man in Northern Ireland until his arrest following a shoot-out with the Special Air Service (SAS) in which an SAS soldier was killed. At his trial, he was sentenced to a total of 83 years' imprisonment; he died during the 1981 Irish hunger strike in HM Prison Maze. Passage 5: Raymond McCreesh Raymond McCreesh (Irish: "Réamonn Mac Raois" , 25 February 1957 – 21 May 1981) was a volunteer in the South Armagh Brigade of the Provisional Irish Republican Army (IRA). In 1976, he and two other IRA volunteers were captured while attempting to ambush a British Army observation post. McCreesh was one of the ten Irish republicans who died in the 1981 Irish hunger strike in the Maze Prison. Passage 6: Roll of Honour (song) Roll of Honour is an Irish Republican song, written by Gerry O'Glacain, that commemorates the 10 IRA and INLA hunger strikers who died during the 1981 Irish hunger strike in Northern Ireland. The names each of the men are contained in the lyrics of the song in the order that they died: Bobby Sands, (Francis) Hughes, Ray McCreesh, (Patsy) O'Hara, Joe McDonnell, Martin Hurson, Kevin Lynch, Kieran Doherty, Thomas McElwee and Michael Devine. The song describes the 10 as "Ireland’s bravest men" who were "Hungering for justice" and "For their rights as Irish soldiers and to free their native land". The song ends with the call to "Fight on and make our homeland a nation once again". Passage 7: Steve McQueen (director) Steven Rodney "Steve" McQueen (born 9 October 1969) is an English film director, producer, screenwriter, and video artist. For his 2013 film, "12 Years a Slave", a historical drama adaptation of an 1853 slave narrative memoir, he won an Academy Award, BAFTA Award for Best Film, and Golden Globe Award for Best Motion Picture – Drama, as a producer, and he also received the award for Best Director from the New York Film Critics Circle. McQueen is the first black filmmaker to win an Academy Award for Best Picture. McQueen is known for his collaborations with actor Michael Fassbender, who has starred in all three of McQueen's feature films as of 2014. McQueen's other feature films are "Hunger" (2008), a historical drama about the 1981 Irish hunger strike, and "Shame" (2011), a drama about an executive struggling with sex addiction. Passage 8: Hunger (2008 film) Hunger is a 2008 British-Irish historical drama film directed by Steve McQueen and starring Michael Fassbender, Liam Cunningham, and Liam McMahon, about the 1981 Irish hunger strike. It was written by Enda Walsh and McQueen. Passage 9: H3 (film) H3 is a film released in 2001 about the 1981 Irish hunger strike at HM Prison Maze in Northern Ireland, the events leading up to it, and subsequent developments in the prisoners' struggle for Prisoner of War status. It was directed by Les Blair and was written by Brian Campbell and Laurence McKeown; McKeown was a former volunteer in the Provisional IRA who participated in the hunger strike. Passage 10: 1981 Irish hunger strike The 1981 Irish hunger strike was the culmination of a five-year protest during The Troubles by Irish republican prisoners in Northern Ireland. The protest began as the blanket protest in 1976, when the British government withdrew Special Category Status for convicted paramilitary prisoners. In 1978, after a number of attacks on prisoners leaving their cells to "slop out", the dispute escalated into the dirty protest, where prisoners refused to leave their cells to wash and covered the walls of their cells with excrement. In 1980, seven prisoners participated in the first hunger strike, which ended after 53 days. Question: What was the name of the character played by Michael Fassbender in a film about the 1981 Irish hunger strike directed by Steve McQueen? Answer: Bobby Sands
{ "task_name": "hotpotqa" }
#region License // // PrimitiveInlineList.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <[email protected]> // // 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. // #endregion #region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using System.Collections.Generic; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>PrimitiveInlineList</c> object is used to convert a /// group of elements in to a collection of element entries. This is /// used when a containing element for a list is not required. It /// extracts the elements by matching elements to name of the type /// that the annotated field or method requires. This enables these /// element entries to exist as siblings to other objects within the /// object. One restriction is that the <c>Root</c> annotation /// for each of the types within the list must be the same. /// </code> /// &lt;entry&gt;example one&lt;/entry&gt; /// &lt;entry&gt;example two&lt;/entry&gt; /// &lt;entry&gt;example three&lt;/entry&gt; /// &lt;entry&gt;example four&lt;/entry&gt; /// </code> /// For the above XML element list the element <c>entry</c> is /// used to wrap the primitive string value. This wrapping XML element /// is configurable and defaults to the lower case string for the name /// of the class it represents. So, for example, if the primitive type /// is an <c>int</c> the enclosing element will be called int. /// </summary> /// <seealso> /// SimpleFramework.Xml.Core.Primitive /// </seealso> /// <seealso> /// SimpleFramework.Xml.ElementList /// </seealso> class PrimitiveInlineList : Repeater { /// <summary> /// This factory is used to create a suitable collection list. /// </summary> private readonly CollectionFactory factory; /// <summary> /// This performs the traversal used for object serialization. /// </summary> private readonly Primitive root; /// <summary> /// This is the name that each list element is wrapped with. /// </summary> private readonly String parent; /// <summary> /// This is the type of object that will be held in the list. /// </summary> private readonly Type entry; /// <summary> /// Constructor for the <c>PrimitiveInlineList</c> object. /// This is given the list type and entry type to be used. The list /// type is the <c>Collection</c> implementation that is used /// to collect the deserialized entry objects from the XML source. /// </summary> /// <param name="context"> /// this is the context object used for serialization /// </param> /// <param name="type"> /// this is the collection type for the list used /// </param> /// <param name="entry"> /// the entry type to be stored within the list /// </param> /// <param name="parent"> /// this is the name to wrap the list element with /// </param> public PrimitiveInlineList(Context context, Type type, Type entry, String parent) { this.factory = new CollectionFactory(context, type); this.root = new Primitive(context, entry); this.parent = parent; this.entry = entry; } /// <summary> /// This <c>read</c> method wll read the XML element list from /// the provided node and deserialize its children as entry types. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Read(InputNode node) { Object value = factory.Instance; Collection list = (Collection) value; if(list != null) { return Read(node, list); } return null; } /// <summary> /// This <c>read</c> method wll read the XML element list from /// the provided node and deserialize its children as entry types. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Read(InputNode node, Object value) { Collection list = (Collection) value; if(list != null) { return Read(node, list); } return Read(node); } /// <summary> /// This <c>read</c> method wll read the XML element list from /// the provided node and deserialize its children as entry types. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <param name="list"> /// this is the collection that is to be populated /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Read(InputNode node, Collection list) { InputNode from = node.getParent(); String name = node.getName(); while(node != null) { Object item = root.Read(node); if(item != null) { list.add(item); } node = from.getNext(name); } return list; } /// <summary> /// This <c>read</c> method wll read the XML element list from /// the provided node and deserialize its children as entry types. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public bool Validate(InputNode node) { InputNode from = node.getParent(); String name = node.getName(); while(node != null) { bool valid = root.Validate(node); if(valid == false) { return false; } node = from.getNext(name); } return true; } /// <summary> /// This <c>write</c> method will write the specified object /// to the given XML element as as list entries. Each entry within /// the given list must be assignable to the given primitive type. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="source"> /// this is the source collection to be serialized /// </param> /// <param name="node"> /// this is the XML element container to be populated /// </param> public void Write(OutputNode node, Object source) { OutputNode parent = node.getParent(); Mode mode = node.getMode(); if(!node.isCommitted()) { node.remove(); } Write(parent, source, mode); } /// <summary> /// This <c>write</c> method will write the specified object /// to the given XML element as as list entries. Each entry within /// the given list must be assignable to the given primitive type. /// This will deserialize each entry type as a primitive value. In /// order to do this the parent string provided forms the element. /// </summary> /// <param name="node"> /// this is the parent output node to write values to /// </param> /// <param name="source"> /// this is the source collection to be serialized /// </param> /// <param name="mode"> /// this is used to determine whether to output CDATA /// </param> public void Write(OutputNode node, Object source, Mode mode) { Collection list = (Collection) source; for(Object item : list) { if(item != null) { OutputNode child = node.getChild(parent); if(!IsOverridden(child, item)) { child.setMode(mode); root.Write(child, item); } } } } /// <summary> /// This is used to determine whether the specified value has been /// overridden by the strategy. If the item has been overridden /// then no more serialization is require for that value, this is /// effectively telling the serialization process to stop writing. /// </summary> /// <param name="node"> /// the node that a potential override is written to /// </param> /// <param name="value"> /// this is the object instance to be serialized /// </param> /// <returns> /// returns true if the strategy overrides the object /// </returns> public bool IsOverridden(OutputNode node, Object value) { return factory.setOverride(entry, value, node); } } }
{ "task_name": "lcc" }
Passage 1: City Girl (1984 film) City Girl is a 1984 film directed by Martha Coolidge. The film was produced in 1982, although it did not receive distribution until Coolidge's 1983 film "Valley Girl" became a surprise success. Passage 2: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 3: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Passage 4: Kátia Lund Kátia Lund( born 1966) is a Brazilian film director and screenwriter. Her most notable work was as co-director of the film" City of God". Passage 5: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 6: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 7: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 8: John Donatich John Donatich is the Director of Yale University Press. Passage 9: Mary Duncan Mary Duncan (August 13, 1894 – May 9, 1993) was an American stage and silent film actress. She is best known for her performances in F.W. Murnau's "City Girl" (1930) and "Morning Glory" (1933). Passage 10: Martha Coolidge Martha Coolidge (born August 17, 1946) is an American film director and former President of the Directors Guild of America. She has directed such films as "Real Genius" and "Rambling Rose". Question: Which country the director of film City Girl (1984 Film) is from? Answer: America
{ "task_name": "2WikiMultihopQA" }
package synergynet3.studentmenucontrol; import java.util.ArrayList; import java.util.logging.Level; import multiplicity3.csys.factory.ContentTypeNotBoundException; import multiplicity3.csys.stage.IStage; import synergynet3.SynergyNetApp; import synergynet3.additionalUtils.AdditionalSynergyNetUtilities; import synergynet3.cluster.SynergyNetCluster; import synergynet3.databasemanagement.DatabaseActivity; import synergynet3.personalcontentcontrol.StudentRepresentation; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; /** * The Class StudentMenuUtilities. */ public class StudentMenuUtilities { /** Student menus currently present in the environment. */ public static ArrayList<StudentMenu> studentMenus = new ArrayList<StudentMenu>(); /** Students currently logged in on the device. */ public static ArrayList<StudentRepresentation> studentRepresentations = new ArrayList<StudentRepresentation>(); /** * Brings all student menus and menu icons to the top of the environment. */ public static void bringAllStudentsToTop(IStage stage) { for (StudentMenu menu : studentMenus) { stage.getZOrderManager().bringToTop(menu.getRadialMenu()); } } /** * Creates a student menu for a given student representation. * * @param student * The student representation to create a student menu for. * @return The student menu item created for the corresponding student. **/ public static StudentMenu generateStudentMenu(StudentRepresentation student, IStage stage, SynergyNetApp app) { StudentMenu menu = new StudentMenu(student, stage, null, app); try { app.modifyMenus(menu); } catch (ContentTypeNotBoundException e) { AdditionalSynergyNetUtilities.log(Level.SEVERE, "Content not Bound", e); } student.getGallery().setMenu(menu); return menu; } /** * Will log in a student with the supplied ID. When a student is logged in * their representation is retrieved from the database service using their * ID and a menu for the student is created and positioned randomly in the * environment. When a student logs in their personal gallery is also * created and populated using details from their database entry. * * @param studentID * ID of the student to be logged in. * @return The student menu item created for the corresponding student. **/ public static StudentMenu login(String studentID, IStage stage, SynergyNetApp app) { for (StudentRepresentation studentRepresentation : studentRepresentations) { if (studentRepresentation.getStudentId().equalsIgnoreCase(studentID)) { return null; } } int displayWidth = (int) (stage.getWorldLocation().x * 2); int displayHeight = (int) (stage.getWorldLocation().y * 2); StudentRepresentation studentRepresentation = DatabaseActivity.getStudentRepresentationFromDatabase(studentID, SynergyNetCluster.get().getXMPPConnection().getHost(), stage); StudentMenu menu = StudentMenuUtilities.generateStudentMenu(studentRepresentation, stage, app); menu.getRadialMenu().setRelativeLocation(new Vector2f((FastMath.rand.nextFloat() * (displayWidth - 40)) - ((displayWidth - 40) / 2), (FastMath.rand.nextFloat() * (displayHeight - 40)) - ((displayHeight - 40) / 2))); menu.getRadialMenu().setRelativeRotation(FastMath.DEG_TO_RAD * (FastMath.rand.nextFloat() * 360f)); menu.setVisibility(true); studentMenus.add(menu); studentRepresentations.add(studentRepresentation); return menu; } /** * Logs out a specific student from the environment and removes their menu. * When logging out their details, such as items and feedback stored in * their personal gallery, are updated in the database. * * @param studentID * ID of the student to be logged out. **/ public static void logout(String studentID, IStage stage) { int toRemove = -1; for (int i = 0; i < studentRepresentations.size(); i++) { if (studentID.equals(studentRepresentations.get(i).getStudent().getStudentID())) { toRemove = i; break; } } if (toRemove >= 0) { try { DatabaseActivity.updateStudentRep(studentRepresentations.get(toRemove), SynergyNetCluster.get().getXMPPConnection().getHost()); studentRepresentations.get(toRemove).getGallery().removeFrom(stage); studentMenus.get(toRemove).removeMenu(stage); studentRepresentations.remove(toRemove); studentMenus.remove(toRemove); } catch (NullPointerException e) { } } } /** * Logs out all students in the environment and removes their menus. **/ public static void logoutAll(IStage stage) { for (int i = 0; i < studentRepresentations.size(); i++) { try { DatabaseActivity.updateStudentRep(studentRepresentations.get(i), SynergyNetCluster.get().getXMPPConnection().getHost()); } catch (NullPointerException e) { } studentRepresentations.get(i).getGallery().removeFrom(stage); studentMenus.get(i).removeMenu(stage); } studentRepresentations.clear(); studentMenus.clear(); } /** * Logs out all students belonging to a specific class. * * @param className * Name of the class for which all students belonging to it * should be logged out. */ public static void logoutAllOfClass(String className, IStage stage) { ArrayList<StudentRepresentation> studentsToRemove = new ArrayList<StudentRepresentation>(); ArrayList<StudentMenu> menusToRemove = new ArrayList<StudentMenu>(); for (int i = 0; i < studentRepresentations.size(); i++) { try { if (studentRepresentations.get(i).getStudent().getClassName().equalsIgnoreCase(className)) { DatabaseActivity.updateStudentRep(studentRepresentations.get(i), SynergyNetCluster.get().getXMPPConnection().getHost()); studentRepresentations.get(i).getGallery().removeFrom(stage); studentMenus.get(i).removeMenu(stage); studentsToRemove.add(studentRepresentations.get(i)); menusToRemove.add(studentMenus.get(i)); } } catch (NullPointerException e) { } } for (StudentRepresentation student : studentsToRemove) { studentRepresentations.remove(student); } for (StudentMenu menu : menusToRemove) { studentMenus.remove(menu); } } /** * Sets whether students representations present in the environment can add * content from their personal galleries to the applications. * * @param allowGalleryAdd * true = items can be added from personal galleries. false = * items cannot be added from personal galleries. **/ public static void setAbilityToAddContentFromGallery(boolean allowGalleryAdd) { for (StudentRepresentation studentRepresentation : studentRepresentations) { studentRepresentation.getGallery().setAbilityToAddContentFromGallery(allowGalleryAdd); } } }
{ "task_name": "lcc" }
package org.apache.archiva.remotedownload; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.archiva.admin.model.beans.RemoteRepository; import org.apache.archiva.redback.rest.api.services.RoleManagementService; import org.apache.archiva.security.common.ArchivaRoleConstants; import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; import org.apache.commons.io.FileUtils; import org.apache.maven.wagon.providers.http.HttpWagon; import org.apache.maven.wagon.repository.Repository; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * @author Olivier Lamy */ @RunWith( ArchivaBlockJUnit4ClassRunner.class ) public class DownloadArtifactsTest extends AbstractDownloadTest { protected Logger log = LoggerFactory.getLogger( DownloadArtifactsTest.class ); public Server redirectServer = null; public int redirectPort; public Server repoServer = null; public int repoServerPort; @BeforeClass public static void setAppServerBase() { previousAppServerBase = System.getProperty( "appserver.base" ); System.setProperty( "appserver.base", "target/" + DownloadArtifactsTest.class.getName() ); } @AfterClass public static void resetAppServerBase() { System.setProperty( "appserver.base", previousAppServerBase ); } @Override protected String getSpringConfigLocation() { return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml"; } @Override @Before public void startServer() throws Exception { super.startServer(); // repo handler this.repoServer = new Server( ); ServerConnector repoServerConnector = new ServerConnector( this.repoServer, new HttpConnectionFactory()); this.repoServer.addConnector( repoServerConnector ); ServletHolder shRepo = new ServletHolder( RepoServlet.class ); ServletContextHandler contextRepo = new ServletContextHandler(); contextRepo.setContextPath( "/" ); contextRepo.addServlet( shRepo, "/*" ); repoServer.setHandler( contextRepo ); repoServer.start(); this.repoServerPort = repoServerConnector.getLocalPort(); //redirect handler this.redirectServer = new Server( ); ServerConnector redirectServerConnector = new ServerConnector( this.redirectServer, new HttpConnectionFactory()); this.redirectServer.addConnector( redirectServerConnector ); ServletHolder shRedirect = new ServletHolder( RedirectServlet.class ); ServletContextHandler contextRedirect = new ServletContextHandler(); contextRedirect.setAttribute( "redirectToPort", Integer.toString( this.repoServerPort ) ); contextRedirect.setContextPath( "/" ); contextRedirect.addServlet( shRedirect, "/*" ); redirectServer.setHandler( contextRedirect ); redirectServer.start(); this.redirectPort = redirectServerConnector.getLocalPort(); log.info( "redirect server port {}", redirectPort ); } @After @Override public void tearDown() throws Exception { super.tearDown(); if ( this.redirectServer != null ) { this.redirectServer.stop(); } } @Test public void downloadWithRemoteRedirect() throws Exception { RemoteRepository remoteRepository = getRemoteRepositoriesService().getRemoteRepository( "central" ); remoteRepository.setUrl( "http://localhost:" + redirectPort ); getRemoteRepositoriesService().updateRemoteRepository( remoteRepository ); RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader ); if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal" ) ) { roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal" ); } getUserService( authorizationHeader ).createGuestUser(); roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" ); roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal", "guest" ); getUserService( authorizationHeader ).removeFromCache( "guest" ); Path file = Paths.get( "target/junit-4.9.jar" ); Files.deleteIfExists( file ); HttpWagon httpWagon = new HttpWagon(); httpWagon.connect( new Repository( "foo", "http://localhost:" + port ) ); httpWagon.get( "repository/internal/junit/junit/4.9/junit-4.9.jar", file.toFile() ); ZipFile zipFile = new ZipFile( file.toFile() ); List<String> entries = getZipEntriesNames( zipFile ); ZipEntry zipEntry = zipFile.getEntry( "org/junit/runners/JUnit4.class" ); assertNotNull( "cannot find zipEntry org/junit/runners/JUnit4.class, entries: " + entries + ", content is: " + FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8") ), zipEntry ); zipFile.close(); file.toFile().deleteOnExit(); } public static class RedirectServlet extends HttpServlet { @Override protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { LoggerFactory.getLogger( getClass() ).info( "redirect servlet receive: {}", req.getRequestURI() ); resp.setStatus( 302 ); resp.getWriter().write( "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>302 Found</title>\n" + "</head><body>\n" + "<h1>Found</h1>\n" + "<p>The document has moved <a href=\"http://repo.maven.apache.org/maven2/junit/junit/4.9/junit-4.9.jar\">here</a>.</p>\n" + "</body></html>\n" + "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" ); resp.sendRedirect( "http://localhost:" + getServletContext().getAttribute( "redirectToPort" ) + "/maven2/" + req.getRequestURI() ); } } public static class RepoServlet extends HttpServlet { @Override protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { Path jar = Paths.get( System.getProperty( "basedir" ), "src/test/junit-4.9.jar" ); Files.copy( jar, resp.getOutputStream() ); } } }
{ "task_name": "lcc" }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vfs.newvfs.impl; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingRegistry; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl; import com.intellij.util.LocalTimeCounter; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.text.StringFactory; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.charset.Charset; /** * @author max */ public abstract class VirtualFileSystemEntry extends NewVirtualFile { public static final VirtualFileSystemEntry[] EMPTY_ARRAY = new VirtualFileSystemEntry[0]; static final PersistentFS ourPersistence = PersistentFS.getInstance(); private static final Key<String> SYMLINK_TARGET = Key.create("local.vfs.symlink.target"); static final int IS_WRITABLE_FLAG = 0x01000000; static final int IS_HIDDEN_FLAG = 0x02000000; private static final int INDEXED_FLAG = 0x04000000; static final int CHILDREN_CACHED = 0x08000000; // makes sense for directory only static final int SYSTEM_LINE_SEPARATOR_DETECTED = CHILDREN_CACHED; // makes sense for non-directory file only private static final int DIRTY_FLAG = 0x10000000; static final int IS_SYMLINK_FLAG = 0x20000000; private static final int HAS_SYMLINK_FLAG = 0x40000000; static final int IS_SPECIAL_FLAG = 0x80000000; static final int ALL_FLAGS_MASK = DIRTY_FLAG | IS_SYMLINK_FLAG | HAS_SYMLINK_FLAG | IS_SPECIAL_FLAG | IS_WRITABLE_FLAG | IS_HIDDEN_FLAG | INDEXED_FLAG | CHILDREN_CACHED; final VfsData.Segment mySegment; private final VirtualDirectoryImpl myParent; final int myId; static { //noinspection ConstantConditions assert (~ALL_FLAGS_MASK) == LocalTimeCounter.TIME_MASK; } VirtualFileSystemEntry(int id, @NotNull VfsData.Segment segment, @Nullable VirtualDirectoryImpl parent) { mySegment = segment; myId = id; myParent = parent; } void updateLinkStatus() { boolean isSymLink = is(VFileProperty.SYMLINK); if (isSymLink) { String target = getParent().getFileSystem().resolveSymLink(this); setLinkTarget(target != null ? FileUtil.toSystemIndependentName(target) : null); } setFlagInt(HAS_SYMLINK_FLAG, isSymLink || getParent().getFlagInt(HAS_SYMLINK_FLAG)); } @Override @NotNull public String getName() { return getNameSequence().toString(); } @NotNull @Override public CharSequence getNameSequence() { return FileNameCache.getVFileName(getNameId()); } public final int getNameId() { return mySegment.getNameId(myId); } @Override public VirtualDirectoryImpl getParent() { VirtualDirectoryImpl changedParent = mySegment.vfsData.getChangedParent(myId); return changedParent != null ? changedParent : myParent; } @Override public boolean isDirty() { return getFlagInt(DIRTY_FLAG); } @Override public long getModificationStamp() { return mySegment.getModificationStamp(myId); } public void setModificationStamp(long modificationStamp) { mySegment.setModificationStamp(myId, modificationStamp); } boolean getFlagInt(int mask) { return mySegment.getFlag(myId, mask); } void setFlagInt(int mask, boolean value) { mySegment.setFlag(myId, mask, value); } public boolean isFileIndexed() { return getFlagInt(INDEXED_FLAG); } public void setFileIndexed(boolean indexed) { setFlagInt(INDEXED_FLAG, indexed); } @Override public void markClean() { setFlagInt(DIRTY_FLAG, false); } @Override public void markDirty() { if (!isDirty()) { markDirtyInternal(); VirtualFileSystemEntry parent = getParent(); if (parent != null) parent.markDirty(); } } void markDirtyInternal() { setFlagInt(DIRTY_FLAG, true); } @Override public void markDirtyRecursively() { markDirty(); for (VirtualFile file : getCachedChildren()) { ((NewVirtualFile)file).markDirtyRecursively(); } } @NotNull protected char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef) { CharSequence name = FileNameCache.getVFileName(mySegment.getNameId(myId)); char[] chars = getParent().appendPathOnFileSystem(accumulatedPathLength + 1 + name.length(), positionRef); int i = positionRef[0]; chars[i] = '/'; positionRef[0] = copyString(chars, i + 1, name); return chars; } protected static int copyString(@NotNull char[] chars, int pos, @NotNull CharSequence s) { int length = s.length(); CharArrayUtil.getChars(s, chars, 0, pos, length); return pos + length; } @Override @NotNull public String getUrl() { String protocol = getFileSystem().getProtocol(); int prefixLen = protocol.length() + "://".length(); char[] chars = appendPathOnFileSystem(prefixLen, new int[]{prefixLen}); copyString(chars, copyString(chars, 0, protocol), "://"); return StringFactory.createShared(chars); } @Override @NotNull public String getPath() { return StringFactory.createShared(appendPathOnFileSystem(0, new int[]{0})); } @Override public void delete(final Object requestor) throws IOException { ApplicationManager.getApplication().assertWriteAccessAllowed(); ourPersistence.deleteFile(requestor, this); } @Override public void rename(final Object requestor, @NotNull @NonNls final String newName) throws IOException { ApplicationManager.getApplication().assertWriteAccessAllowed(); if (getName().equals(newName)) return; validateName(newName); ourPersistence.renameFile(requestor, this, newName); } @Override @NotNull public VirtualFile createChildData(final Object requestor, @NotNull final String name) throws IOException { validateName(name); return ourPersistence.createChildFile(requestor, this, name); } @Override public boolean isWritable() { return getFlagInt(IS_WRITABLE_FLAG); } @Override public void setWritable(boolean writable) throws IOException { ourPersistence.setWritable(this, writable); } @Override public long getTimeStamp() { return ourPersistence.getTimeStamp(this); } @Override public void setTimeStamp(final long time) throws IOException { ourPersistence.setTimeStamp(this, time); } @Override public long getLength() { return ourPersistence.getLength(this); } @NotNull @Override public VirtualFile copy(final Object requestor, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException { if (getFileSystem() != newParent.getFileSystem()) { throw new IOException(VfsBundle.message("file.copy.error", newParent.getPresentableUrl())); } if (!newParent.isDirectory()) { throw new IOException(VfsBundle.message("file.copy.target.must.be.directory")); } return EncodingRegistry.doActionAndRestoreEncoding(this, () -> ourPersistence.copyFile(requestor, this, newParent, copyName)); } @Override public void move(final Object requestor, @NotNull final VirtualFile newParent) throws IOException { ApplicationManager.getApplication().assertWriteAccessAllowed(); if (getFileSystem() != newParent.getFileSystem()) { throw new IOException(VfsBundle.message("file.move.error", newParent.getPresentableUrl())); } EncodingRegistry.doActionAndRestoreEncoding(this, () -> { ourPersistence.moveFile(requestor, this, newParent); return this; }); } @Override public int getId() { return mySegment.vfsData.isFileValid(myId) ? myId : -myId; } @Override public boolean equals(Object o) { return this == o || o instanceof VirtualFileSystemEntry && myId == ((VirtualFileSystemEntry)o).myId; } @Override public int hashCode() { return myId; } @Override @NotNull public VirtualFile createChildDirectory(final Object requestor, @NotNull final String name) throws IOException { validateName(name); return ourPersistence.createChildDirectory(requestor, this, name); } private void validateName(@NotNull String name) throws IOException { if (!getFileSystem().isValidName(name)) { throw new IOException(VfsBundle.message("file.invalid.name.error", name)); } } @Override public boolean exists() { return mySegment.vfsData.isFileValid(myId); } @Override public boolean isValid() { return exists(); } @Override public String toString() { return getUrl(); } public void setNewName(@NotNull String newName) { if (!getFileSystem().isValidName(newName)) { throw new IllegalArgumentException(VfsBundle.message("file.invalid.name.error", newName)); } VirtualDirectoryImpl parent = getParent(); parent.removeChild(this); mySegment.setNameId(myId, FileNameCache.storeName(newName)); parent.addChild(this); ((PersistentFSImpl)PersistentFS.getInstance()).incStructuralModificationCount(); } public void setParent(@NotNull VirtualFile newParent) { ApplicationManager.getApplication().assertWriteAccessAllowed(); VirtualDirectoryImpl parent = getParent(); parent.removeChild(this); VirtualDirectoryImpl directory = (VirtualDirectoryImpl)newParent; mySegment.vfsData.changeParent(myId, directory); directory.addChild(this); updateLinkStatus(); ((PersistentFSImpl)PersistentFS.getInstance()).incStructuralModificationCount(); } @Override public boolean isInLocalFileSystem() { return getFileSystem() instanceof LocalFileSystem; } public void invalidate() { mySegment.vfsData.invalidateFile(myId); } @NotNull @Override public Charset getCharset() { return isCharsetSet() ? super.getCharset() : computeCharset(); } @NotNull private Charset computeCharset() { Charset charset; if (isDirectory()) { Charset configured = EncodingManager.getInstance().getEncoding(this, true); charset = configured == null ? Charset.defaultCharset() : configured; setCharset(charset); } else { FileType fileType = getFileType(); if (isCharsetSet()) { // file type detection may have cached the charset, no need to re-detect return super.getCharset(); } try { final byte[] content = VfsUtilCore.loadBytes(this); charset = LoadTextUtil.detectCharsetAndSetBOM(this, content, fileType); } catch (IOException e) { return super.getCharset(); } } return charset; } @Override public String getPresentableName() { if (UISettings.getInstance().getHideKnownExtensionInTabs() && !isDirectory()) { final String nameWithoutExtension = getNameWithoutExtension(); return nameWithoutExtension.isEmpty() ? getName() : nameWithoutExtension; } return getName(); } @Override public boolean is(@NotNull VFileProperty property) { if (property == VFileProperty.SPECIAL) return getFlagInt(IS_SPECIAL_FLAG); if (property == VFileProperty.HIDDEN) return getFlagInt(IS_HIDDEN_FLAG); if (property == VFileProperty.SYMLINK) return getFlagInt(IS_SYMLINK_FLAG); return super.is(property); } public void updateProperty(@NotNull String property, boolean value) { if (property == PROP_WRITABLE) setFlagInt(IS_WRITABLE_FLAG, value); if (property == PROP_HIDDEN) setFlagInt(IS_HIDDEN_FLAG, value); } public void setLinkTarget(@Nullable String target) { putUserData(SYMLINK_TARGET, target); } @Override public String getCanonicalPath() { if (getFlagInt(HAS_SYMLINK_FLAG)) { if (is(VFileProperty.SYMLINK)) { return getUserData(SYMLINK_TARGET); } VirtualFileSystemEntry parent = getParent(); if (parent != null) { return parent.getCanonicalPath() + "/" + getName(); } return getName(); } return getPath(); } @Override public NewVirtualFile getCanonicalFile() { if (getFlagInt(HAS_SYMLINK_FLAG)) { final String path = getCanonicalPath(); return path != null ? (NewVirtualFile)getFileSystem().findFileByPath(path) : null; } return this; } }
{ "task_name": "lcc" }
Passage 1: Brian Kennedy (gallery director) Brian Patrick Kennedy( born 5 November 1961) is an Irish- born art museum director who has worked in Ireland and Australia, and now lives and works in the United States. He is currently the director of the Peabody Essex Museum. He was the director of the Toledo Museum of Art in Ohio from 2010 to 2019. He was the director of the Hood Museum of Art from 2005 to 2010, and the National Gallery of Australia( Canberra) from 1997- 2004. Passage 2: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 3: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 4: Harold Young (director) Harold Young (November 13, 1897 – March 3, 1972) was an American film director, editor, and occasional actor. Born in Portland, Oregon, Young was active as a film editor from 1923-1934, working first on a series of George O'Hara short subjects under the director Malcolm St. Clair. Young's best-known early directorial assignment is probably "The Scarlet Pimpernel" (1934), starring Leslie Howard and Merle Oberon, one example of his occasional work in Britain. He died on March 3, 1972, in Beverly Hills, California. Passage 5: Where Was I " Where Was I?" may refer to: Passage 6: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Passage 7: Pierre Houle Pierre Houle is a Canadian film and television director. He is best known for the 2004 film" Machine Gun Molly( Monica la mitraille)", for which he garnered a Genie Award nomination for Best Director at the 25th Genie Awards. He was also nominated for Best Original Song, as cowriter with Lorraine Richard and Michel Cusson of the song" Le Blues de Monica". He was also a director of the television drama series" Scoop" and" Omerta", and won Gémeaux Awards for Best Director of a Drama Series in 1996 and 1998. Passage 8: Motherland (disambiguation) Motherland is the place of one's birth, the place of one's ancestors, or the place of origin of an ethnic group. Motherland may also refer to: Passage 9: Jesse E. Hobson Jesse Edward Hobson( May 2, 1911 – November 5, 1970) was the director of SRI International from 1947 to 1955. Prior to SRI, he was the director of the Armour Research Foundation. Passage 10: Machine Gun Mama Machine Gun Mama is a 1944 American musical comedy film directed by Harold Young. It was PRC's attempt to feature a comedy team to compete with Universal's Abbott and Costello and Paramount's Road to ... movies and their entry in the Good Neighbor Policy film genre of the time where the United States presented both a positive image to Latin and South America as well as stimulating American tourism to the region. Harold Young had also directed the live action portions of Walt Disney's "The Three Caballeros". The film had the working titles "Mexican Fiesta" and "Moonlight Fiesta" but is also known as Tropical Fury as an American TV title of the film. Question: Where was the place of death of the director of film Machine Gun Mama? Answer: Beverly Hills
{ "task_name": "2WikiMultihopQA" }
Passage 1: Desmond Davis Desmond Davis (born 24 May 1926 in London, England) is a British film and television director. Passage 2: John Donatich John Donatich is the Director of Yale University Press. Passage 3: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 4: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 5: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 6: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 7: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Passage 8: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Passage 9: I Was Happy Here I Was Happy Here is a 1966 drama film directed by Desmond Davis. The film won three awards at the 1966 San Sebastián International Film Festival. The film was released in the U.S. as Time Lost and Time Remembered. Passage 10: Happy Here and Now Happy Here and Now is a 2002 film directed by Michael Almereyda. It has a 45% on Rotten Tomatoes based on 20 reviews. It was nominated for an Independent Spirit Award in 2004. Question: What nationality is the director of film I Was Happy Here? Answer: British
{ "task_name": "2WikiMultihopQA" }
package com.google.ratel.deps.jackson.core.format; import java.io.*; import java.util.*; import com.google.ratel.deps.jackson.core.*; /** * Simple helper class that allows data format (content type) auto-detection, * given an ordered set of {@link JsonFactory} instances to use for actual low-level * detection. */ public class DataFormatDetector { /** * By default we will look ahead at most 64 bytes; in most cases, * much less (4 bytes or so) is needed, but we will allow bit more * leniency to support data formats that need more complex heuristics. */ public final static int DEFAULT_MAX_INPUT_LOOKAHEAD = 64; /** * Ordered list of factories which both represent data formats to * detect (in precedence order, starting with highest) and are used * for actual detection. */ protected final JsonFactory[] _detectors; /** * Strength of match we consider to be good enough to be used * without checking any other formats. * Default value is {@link MatchStrength#SOLID_MATCH}, */ protected final MatchStrength _optimalMatch; /** * Strength of minimal match we accept as the answer, unless * better matches are found. * Default value is {@link MatchStrength#WEAK_MATCH}, */ protected final MatchStrength _minimalMatch; /** * Maximum number of leading bytes of the input that we can read * to determine data format. *<p> * Default value is {@link #DEFAULT_MAX_INPUT_LOOKAHEAD}. */ protected final int _maxInputLookahead; /* /********************************************************** /* Construction /********************************************************** */ public DataFormatDetector(JsonFactory... detectors) { this(detectors, MatchStrength.SOLID_MATCH, MatchStrength.WEAK_MATCH, DEFAULT_MAX_INPUT_LOOKAHEAD); } public DataFormatDetector(Collection<JsonFactory> detectors) { this(detectors.toArray(new JsonFactory[detectors.size()])); } /** * Method that will return a detector instance that uses given * optimal match level (match that is considered sufficient to return, without * trying to find stronger matches with other formats). */ public DataFormatDetector withOptimalMatch(MatchStrength optMatch) { if (optMatch == _optimalMatch) { return this; } return new DataFormatDetector(_detectors, optMatch, _minimalMatch, _maxInputLookahead); } /** * Method that will return a detector instance that uses given * minimal match level; match that may be returned unless a stronger match * is found with other format detectors. */ public DataFormatDetector withMinimalMatch(MatchStrength minMatch) { if (minMatch == _minimalMatch) { return this; } return new DataFormatDetector(_detectors, _optimalMatch, minMatch, _maxInputLookahead); } /** * Method that will return a detector instance that allows detectors to * read up to specified number of bytes when determining format match strength. */ public DataFormatDetector withMaxInputLookahead(int lookaheadBytes) { if (lookaheadBytes == _maxInputLookahead) { return this; } return new DataFormatDetector(_detectors, _optimalMatch, _minimalMatch, lookaheadBytes); } private DataFormatDetector(JsonFactory[] detectors, MatchStrength optMatch, MatchStrength minMatch, int maxInputLookahead) { _detectors = detectors; _optimalMatch = optMatch; _minimalMatch = minMatch; _maxInputLookahead = maxInputLookahead; } /* /********************************************************** /* Public API /********************************************************** */ /** * Method to call to find format that content (accessible via given * {@link InputStream}) given has, as per configuration of this detector * instance. * * @return Matcher object which contains result; never null, even in cases * where no match (with specified minimal match strength) is found. */ public DataFormatMatcher findFormat(InputStream in) throws IOException { return _findFormat(new InputAccessor.Std(in, new byte[_maxInputLookahead])); } /** * Method to call to find format that given content (full document) * has, as per configuration of this detector instance. * * @return Matcher object which contains result; never null, even in cases * where no match (with specified minimal match strength) is found. */ public DataFormatMatcher findFormat(byte[] fullInputData) throws IOException { return _findFormat(new InputAccessor.Std(fullInputData)); } /** * Method to call to find format that given content (full document) * has, as per configuration of this detector instance. * * @return Matcher object which contains result; never null, even in cases * where no match (with specified minimal match strength) is found. * * @since 2.1 */ public DataFormatMatcher findFormat(byte[] fullInputData, int offset, int len) throws IOException { return _findFormat(new InputAccessor.Std(fullInputData, offset, len)); } /* /********************************************************** /* Overrides /********************************************************** */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); final int len = _detectors.length; if (len > 0) { sb.append(_detectors[0].getFormatName()); for (int i = 1; i < len; ++i) { sb.append(", "); sb.append(_detectors[i].getFormatName()); } } sb.append(']'); return sb.toString(); } /* /********************************************************** /* Internal methods /********************************************************** */ private DataFormatMatcher _findFormat(InputAccessor.Std acc) throws IOException { JsonFactory bestMatch = null; MatchStrength bestMatchStrength = null; for (JsonFactory f : _detectors) { acc.reset(); MatchStrength strength = f.hasFormat(acc); // if not better than what we have so far (including minimal level limit), skip if (strength == null || strength.ordinal() < _minimalMatch.ordinal()) { continue; } // also, needs to better match than before if (bestMatch != null) { if (bestMatchStrength.ordinal() >= strength.ordinal()) { continue; } } // finally: if it's good enough match, we are done bestMatch = f; bestMatchStrength = strength; if (strength.ordinal() >= _optimalMatch.ordinal()) { break; } } return acc.createMatcher(bestMatch, bestMatchStrength); } }
{ "task_name": "lcc" }
Passage: Chemical Element: roentgenium - Word Information Chemical Element: roentgenium (Named for German physicist Wilhelm Conrad Roentgen) Chemical-Element Information Atomic number: 111 Year discovered: 1994 Discovered by: S. Hofmann, V. Ninov, F. P. Hessberger, P. Armbruster, H. Folger, G. Münzenberg, H. J. Schott, A. G. Popeko, A. V. Yeremin, A. N. Andreyev, S. Saro, R. Janik, M. Lein, and others at GSI in Darmstadt, Germany. Röntgen, or Roentgen, was born on March 27, 1845, in Lennkep, Prussia (now Remscheid, Germany) and died on February 10, 1923 in Munich, Germany. Wilhelm Conrad Röntgen, as a German physicist, discovered X-rays on 8 November 1895, a new type of rays to which he gave this name in view of their uncertain nature. Their use has subsequently revolutionized medicine, found wide application in technology, and heralded the age of modern physics, which is based on atomic and nuclear properties. In 1901, six years after their discovery, the benefit of X-rays to mankind was so evident that Roentgen was awarded the first Nobel Prize in Physics. His discovery of "x-rays" significantly contributed to modern physics and revolutionized diagnostic medicine. Röntgen studied at the Polytechnic in ZŸrich and then was professor of physics at the universities of Strasbourg (1876-79), Giessen (1879-88), Würzburg (1888-1900), and Munich (1900-20). His research also included work on elasticity, capillary action of fluids, specific heats of gases, conduction of heat in crystals, absorption of heat by gases, and piezoelectricity. Röntgen determined that because the X-rays were not deflected by a magnet, they could not be a form of cathode rays. He speculated that instead the X-rays might be longitudinal electromagnetic waves. The possible medical use of X-rays was realized almost immediately. Unlike other discoveries where the practical applications follow only after decades, physicians were using X-rays within months to inspect internal damage without surgery. Today we know that X-rays are high energy, transverse electromagnetic waves similar to other forms of light. Electromagnetic radiation ranges from high energy, short wave-length gamma and X-rays, through ultraviolet light, visible light, and infrared, to low energy, and long wave-length radio waves. Despite the fact that Röntgen discovered nearly all the properties of X-rays within the first few weeks of investigation, the temporary name he used (X-rays) for the sake of brevity remains the name that is still generally used today (except in Germany where they usually refer to a "Röntgen" examination or report). Element 111 was synthesized exactly 100 years after Roentgen's discovery. To honor Wilhelm Conrad Roentgen, the name, roentgenium, was proposed for the element with atomic number 111. The name roentgenium for the element of atomic number 111 (with symbol Rg) was officially approved as of November 1, 2004. Name in other languages: Question: Which chemical element is named after the German physicist who discovered X-Rays? Answer: {'aliases': ['Röntgenium', 'Eka-Gold', 'Rogentium', 'Eka-gold', 'ROENTGENIUM', 'Roentgenium', 'Roentogenium', 'Unununium the element 111', 'Element 111', 'Uninunium', 'Unununium', 'Unununium (element)', 'Unununium element 111'], 'normalized_aliases': ['unununium element 111', 'eka gold', 'roentogenium', 'element 111', 'rogentium', 'unununium', 'uninunium', 'unununium element', 'röntgenium', 'roentgenium'], 'matched_wiki_entity_name': '', 'normalized_matched_wiki_entity_name': '', 'normalized_value': 'roentgenium', 'type': 'WikipediaEntity', 'value': 'ROENTGENIUM'} Passage: Heavy Metals, Mining, General Industry in LusakaZambia | Kafue River Basin Heavy Industry, Fertilizers, General Industry, Mining The problem The Kafue River Basin in the Chingola District, Zambia has experienced heavy polluting over the past several decades. Konkola Copper Mines (KCM) is the primary source of this pollution, disposing of industrial waste products and various bio-chemical substances directly into the reservoirs. They are not the only polluters, however, as the region is home to roughly 40% of the nation’s socio-economic activity; a range of other industries are also at fault for the current state of the river basin: pulp-and-paper mills, fertilizer factories, granulation plants, abattoirs, textile manufacturers, and more. More than 93,000 tons of industrial waste are produced annually, most of which finds it way into the Kafue River. From there it flows into the Zambezi River – Africa’s fourth largest – that claims Zambia as its source and winds through Angola, Namibia, Botswana, Zimbabwe, and Mozambique before eventually emptying out into the Indian Ocean. As a result of the pollution, the steadily increasing population in the Chingola District face severe water shortages. The full extent of the environmental impact has not yet been determined, but because of significant habitat destruction and land/soil degradation, the cost to local ecosystems is likely quite high. The color of the brilliantly blue Kafue River has slowly turned green. Indigenous fish have developed an unusual and unpleasant odor. Aquatic weeds dumped by some facilities into the river system, combined with nitrogen and phosphate waste from other facilities, together degrade biodiversity. Both aquatic life and human health are in danger. High incidences of environmentally mediated disease, such as gastro-enteritis, intestinal worms, and diarrhea diseases mostly in children have been reported from communities around the river and have been linked to drinking water from certain parts of the river. The raw sewer pollution of Kafue River could inadvertently lead to outbreaks of epidemics like cholera. Current Activity Our strategy involved a three-pronged approach: extensive surveys of current pollution levels, strategic monitoring of KCM and other industrial waste disposal, and the development of novel weed control technologies. The first stage involved surveying the most dramatically polluted sites along the Kafue River basin. Once the sites were identified, they were brought to the attention of stakeholder groups (including the local communities and polluting companies) and policy makers, methods were suggested to treat or reduce pollution levels and a dialogue was promoted between our team and interested parties at all levels of the existing socio-economic framework. Data dissemination was facilitated through workshops and community meetings. Essentially, the primary focus of this first stage was awareness and education. The second phase of our strategy focused on GPS monitoring systems. We demonstrated how GPS can be used as a cost-effective method of tracking pollution and polluters, that additionally could be made available to much of sub-Saharan Africa. We also promoted a physical inspection timeline where the resources necessary to acquire GPS systems were not available. Although law enforcement is poor and institutional systems are weak, the third stage of our approach called for management protocols that addressed weed control and other forms of pollution in the Kafue river basin. By involving the stakeholder groups, we sought to prioritize the long-term effects of environmentalists working to improve the river’s quality and develop a form of systematic follow-up. Outcome ARE is focusing its efforts on compelling the Kafue Sewage Treatment Plant, the Bata Tannery, Kafue Nitrogen Chemicals, and Lee Yeast to establish cleaner production and waste treatment methods that will minimize harmful discharge into the river. ARE is currently lobbying the Ministry of Local Government and Housing, the National Water and Sanitation Council, and multilateral cooperating partners to bring about a stop to the dumping. Recently, ARE has worked with the local administration and industry to bring about production process improvements in Bata Tannery, such as reduction and reuse of effluent streams and more thorough wastewater treatment. Future Plans: ARE continues to work on advocating for improvements in operation at Kafue Sewage Treatment Plant, in addition to participating in various African networks on water quality. ARE continuously monitors pollution streams from industrial plants. Blacksmith is working with NGOs, the local administration and industry to reduce pollution of the Kafue River from copper mines, metallurgical plants, textile plants, fertilizer factories, sugar processing plants, cement factories, various agricultural activities, and the Kafue Sewage Treatment Plant (KSTP). The Kafue River, part of the Zambezi basin, is a source of potable water for over forty percent of Zambia's population. For decades, Mineral deposits, chemicals, and suspended solids have led to overgrowth of aquatic weeds, choking river life. By helping the coalition to implement the reduction and reuse of effluent streams and more thorough wastewater treatment, the river is on its way to recovery. Question: Which river has its source in Zambia and flows through Angola, Namibia, Botswana and Zimbabwe before emptying into the Indian Ocean in Mozambique? Answer: {'aliases': ['Zambesi', 'Zambezi river', 'Zambezi basin', 'Zambezi Valley', 'Zambesi river', 'Zambeze River', 'Zambesi River', 'Zambezian coastal flooded savanna', 'Kabra Bassa rapids', 'River Zambezi', 'Sambesi', 'Great Zambezi River', 'Zambezi River', 'Zambezi', 'Zambezi valley', 'ZAMBESI', 'Zambeze'], 'normalized_aliases': ['kabra bassa rapids', 'zambezi river', 'zambezi basin', 'river zambezi', 'great zambezi river', 'zambesi river', 'zambeze river', 'zambezi', 'zambezi valley', 'sambesi', 'zambeze', 'zambesi', 'zambezian coastal flooded savanna'], 'matched_wiki_entity_name': '', 'normalized_matched_wiki_entity_name': '', 'normalized_value': 'zambesi', 'type': 'WikipediaEntity', 'value': 'ZAMBESI'} Passage: Devon | county, England, United Kingdom | Britannica.com county, England, United Kingdom county Devon, administrative, geographic, and historic county of England . It forms part of the South West (or Cornish) Peninsula of Great Britain and is bounded to the west by Cornwall and to the east by Dorset and Somerset . The Bristol Channel lies to the north, and the English Channel abuts it to the south. The shoreline of Lyme Bay at Sidmouth, Devon, England, looking west toward Peak Hill. A.F. Kersting The administrative, geographic, and historic counties cover slightly different areas. The administrative county comprises the districts of East Devon , Mid Devon , North Devon , South Hams , Teignbridge , and Torridge ; the borough of West Devon ; and the city of Exeter , the county seat. The geographic county of Devon is the third largest of that type in England. It encompasses the administrative county and the unitary authorities of Plymouth and Torbay . The historic county comprises the entire geographic county, as well as a small area along the border of the district of West Dorset in the administrative county of Dorset and a larger area extending west from Werrington along the River Otter within the historic district of North Cornwall in the Cornwall unitary authority. Within Devon’s boundaries is a wide variety of scenery, including Dartmoor National Park and, in the north, part of Exmoor National Park . Dartmoor , with shallow marshy valleys, thin infertile soils, and a vegetation of coarse grasses, heather, and bracken, is a granite plateau rising to above 2,000 feet (600 metres), the crests capped by granite tors (isolated weathered rocks); the moor is used for rough grazing, reforestation, reservoirs, and military training and is a popular area for tourists. Exmoor , reaching elevations above 1,575 feet (480 metres), is another plateau where rough grazing and tourism are important, but it has more farmland than Dartmoor. Those two areas of moorland contain the main sources of rivers for the county. From Dartmoor the rivers flow in a radial pattern to the north and south coasts and to the River Tamar (the Cornish boundary); from Exmoor they flow seaward via the River Exe and northward to the Bristol Channel. Much of central and northwestern Devon is given over to grassland. The soils in South Hams, south of Dartmoor, often produce good farmland. The most fertile soil is in southeastern Devon. The county’s generally mild climate becomes more extreme with elevation and distance from the sea, and rainfall increases from about 30 inches (760 mm) on the south coast to more than 60 inches (1,500 mm) on Exmoor and 80 inches (2,000 mm) on Dartmoor. Tor at Sharpitor, near Lustleigh in Dartmoor, Devon, England. © Martin Fowler/Shutterstock.com Wiltshire Prehistoric remains abound; they include the limestone caves near Torquay (including Kent’s Cavern , one of the two oldest human dwellings in Britain), numerous high-altitude Bronze Age remains on Dartmoor, and later Iron Age hill forts and earthworks fringing the moor and guarding river routes. The largest, Hembury Fort, was probably the capital of the Dumnonii, a British tribe, until the foundation of Exeter as a Roman frontier station at the termination of Fosse Way . The Dumnonii survived the 7th-century Saxon conquests, but both Saxon and Briton became subjects of Wessex . Devon was recognized as a shire in the late 8th century and suffered subsequently from Danish raids (851–1003). The Saxons created four strongholds, called burhs, at Exeter, Barnstaple , Totnes , and Lydford. Exeter was taken by the Norman William I the Conqueror in 1068, and a castle was built there in 1348. The Normans also built castles at Totnes, Okehampton , and Plympton; those, like the burhs, acted as nuclei for the growth of towns. Cist near Yelverton, Devon, England. Herbythyme Tin mining on Dartmoor was important from the 12th to the 17th century, and the miners formed a separate community with its own courts. The ports of Exeter, Plymouth, Barnstaple, and Dartmouth thrived from medieval times on the export of tin and cloth (a staple industry) until these both declined in the 19th century, causing rural depopulation that was alleviated only by the rise of tourism, which rapidly increased during the railway era. By the 19th century lead, silver, iron ore, copper, and manganese had all been worked. In 2006 the mine areas in West Devon and nearby Cornwall were designated a UNESCO World Heritage site . Britannica Stories EU Considers Rules For Robots Agriculture is Devon’s most valuable single economic activity; about 30 percent of the working population is dependent on agriculture and related industries. It is based on livestock (supported by permanent grassland and ley), cereals (especially barley), potatoes, market gardening, horticulture, fruit, and fodder crops. About 25 percent of the country is heath or moorland, providing rough grazing mainly on Exmoor and Dartmoor. Dairy cattle are most important in eastern, northwestern, and southern Devon, and Devonshire clotted cream is still produced. Beef cattle are raised throughout, especially in the south and west. Sheep are important throughout the county, including Dartmoor and Exmoor, with the exception of eastern Devon. Between 1964 and 1980 the number of farm holdings fell by 25 percent, but the average size increased. Soft fruit and flowers are grown in sheltered areas, but traditional cider orchards are declining in acreage, and the cider is now produced in factories. Farm in the Blackdown Hills, near Newcott, Devon, England. Derek Harper British Culture and Politics Tourism dominates the coastal areas and is also significant in the rural interior. The main resorts, apart from Ilfracombe on the north coast, lie on the south coast and include Torbay (one of the country’s leading holiday resorts), Paignton, and Brixham . Both coasts abound with picturesque small towns and villages, such as Salcombe, Lynmouth, and Clovelly. Service trades employ two-thirds of the working population, more than the national average, reflecting the importance of tourism and the large retired population that is attracted by the mild winter climate and scenery. The coastal areas of East Devon, as well as those of neighbouring Dorset, were named a World Heritage site (2001). Ilfracombe (district of North Devon), Devon, England. Adrian Pingstone Fishing is still important, especially at Brixham and Plymouth, which also has a naval base. Kaolin (china clay) from Dartmoor and ball clay from the Bovey basin are the chief mineral exports. Local industries include textiles (Tiverton), dairy produce (Totnes), glass (Dartington), woolens (Axminster), lace (Honiton), and the complex industries of the Devonport dockyard. Plymouth and Exeter are the main industrial centres, followed by Torbay, Barnstaple, and Newton Abbot . Connect with Britannica Devon - Student Encyclopedia (Ages 11 and up) The English county of Devon lies on the southwestern peninsula of the island of Great Britain. It is bounded to the west by Cornwall and to the east by Dorset and Somerset. The Bristol Channel lies to the north, and the English Channel is to the south. Devon is an administrative, geographic, and historic county. The administrative county comprises the districts of East Devon, Mid Devon, North Devon, South Hams, Teignbridge, and Torridge; the borough of West Devon; and the city of Exeter, the county seat. The geographic and historic counties of Devon cover slightly different areas. Article History Question: In terms of population, which is the largest city in Devon? Answer: {'aliases': ['The Plymouth', 'PLYMOUTH'], 'normalized_aliases': ['plymouth'], 'matched_wiki_entity_name': '', 'normalized_matched_wiki_entity_name': '', 'normalized_value': 'plymouth', 'type': 'WikipediaEntity', 'value': 'PLYMOUTH'} Passage: Top 10 Rugby Players Of All Time | Terrific Top 10 Counting down to the BEST Top 10 Rugby Players Of All Time by Kyle Rugby is one of the world’s most popular sports, despite only becoming professional in the 90’s.  It has produced many great players throughout the years, and here are the ten I feel are the best.  Several outstanding players had to be left out, because I just couldn’t find a place for them. Honorable Mentions: Bryan Habana, Joost van der Westhuizen, George Gregan, Francois Pienaar, Matt Giteau, Gareth Edwards, Gavin Hastings #10. Shane Williams    Arguably Wales’ greatest ever player, Shane Williams has scored more tries, and had more appearances than any other Welsh player in history.  His breakthrough was in the 2005 Six Nations, where Wales won every single match (a Grand Slam), largely thanks to his tries.  He also led Wales to another Grand Slam in 2008.  That year, he was awarded the IRB rugby player of the year award, the first Welshmen to win the honor.  In his final match, a friendly against Australia in 2011, Shane Williams scored his 58th try with final touch of the ball.  Williams was famous for his acceleration, and his small size, being nicknamed “Little Shane Williams.” #9. Naas Botha    Despite playing during the time when South Africa was almost completely banned from international rugby for Apartheid, Naas Botha was still able to leave his mark on the game.  He was an excellent kicker, who was famous for his ability to score drop-goals under pressure.  In only 28 caps for South Africa, Botha was able to score 312 points, a South African record for decades.  Towards the end of his career, Botha was able to see South Africa rejoin the international fold.  If only his team hadn’t been banned, Botha may have been very near the top of this list. #8. Percy Montgomery    The all-time record holder in both caps and points for South Africa, Percy Montgomery was one of the sport’s greatest kickers.  He was the top points scorer in both the 2004 and 2005 Tri Nation tournaments.  However, his finest moment came in the 2007 World Cup, when his accurate kicking led South Africa to the title of the most prestigious rugby tournament.  Montgomery started off being extremely erratic, as he could play brilliantly one match and then be very poor the next.  However, he was able to sort that out to become one of the sport’s greats. #7. Brian O’Driscoll    O’Driscoll holds the record for the most tries for any centre, his position, in history.  He is also the most capped Irish player, with 83 of his 120 Irish caps being as captain.  In fact, he is the second most-capped player ever.  O’Driscoll was named the player of the tournament at three separate Six Nations – 2006, 2007, and 2009.  In the 2009 edition, he led Ireland to their first Grand Slam in 61 years, and scored a try in every match except one.  He has played for Ireland in the last three World Cups, leading them to the quarterfinals in 2011. #6. Jonny Wilkinson    Wilkinson began his rise in 2001, but really burst onto the scene in 2003.  In one of the most famous World Cup moments, he scored a drop-goal in the last minute of extra time in the final to give England the win against Australia, their only World Cup title.  He suffered a series of injuries in the next few years, and critics argued his best form was behind him.  However, Wilkinson proved them wrong by leading England to the final of the 2007 World Cup, where they lost a close match to South Africa.  He was rugby’s highest point scorer in history, until New Zealand’s Dan Carter surpassed him in mid-2011. #5. Richie McCaw    McCaw was surprisingly chosen for New Zealand’s end-of-2001 tour, despite his inexperience.  But in his debut match against Ireland, he was named man of the match after a brilliant performance.  McCaw became a key part of the New Zealand side, and was named captain in 2006.  He was criticized after New Zealand underperformed at the 2007 World Cup, falling in the quarterfinals.  However, he silenced his critics in the 2011 World Cup, when he brilliantly led his team to the title.  He is a three-time IRB Player of the Year (2006, 2009, and 2010).  Up until 2012, when Carter won his second, no player had won the award more than once. #4. David Campese    One of the most entertaining players to grace rugby, David Campese was capped 101 times for Australia, and held the world record for the most tries in test rugby until 2006.  He was named player of the tournament at the 1991 World Cup, where Australia defeated England in the final.  He was famous for playing to entertain the crowd, while still being able to rack up tries.  Campese was outspoken throughout his career, describing himself as “rugby’s first millionaire”, at a time when players were banned from profiting from rugby.  However, his brilliant play spoke louder than his words, and he still remains an Australian great. #3. Dan Carter    Dan Carter is arguably the greatest kicker in the history of rugby.  He holds the world record for points, which he took from Jonny Wilkinson.  He is the highest point scorer in the history of the Tri Nations (now the Rugby Championship), and has scored 1,381 points in his history.  In 2005, Carter scored 33 points against the British and Irish Lions.  This was nearly double the previous record for a New Zealander in one match.   His performance was called one of the greatest in rugby history.  He has also scored 29 tries, and New Zealand have won every single match he scored a try in. #2. Martin Johnson    In 1993, Martin Johnson was supposed to play a match for his club, but England suddenly needed him after one of their starters had been injured, so he was dramatically thrown on for his debut.  However, he played well as England defeated France.  After that match, Johnson became a regular starter, helping England win the Grand Slam in 1995.  He became captain four years later, and led England to the World Cup title in 2003.  Johnson was appointed English manager in 2008, three years after he had retired.  He was in charge until after the 2011 World Cup, where England underperformed. #1. Jonah Lomu    Jonah Lomu combined speed and power to dazzle opponents.  He is recognized as rugby’s first true superstar, and helped grow the sport during the early 90’s.  Lomu only had two caps entering the 1995 World Cup, but stunned the rugby world by scoring seven tries in five matches.  His tries helped New Zealand to the final, where they lost to South Africa in a historic match.  He remains the highest try scorer in World Cup history, with 12 tries.  He was also crucial to New Zealand winning the first Tri Nations tournament, in 1996.  Throughout his career, Lomu struggled with nephrotic syndrome, a serious kidney disorder.  The disease often left him bedridden on days he wasn’t playing, although he kept it a secret for most of his career. Share this: No he wasn’t ! He ain’t do ish brah !!!!!!! LOMU hands down. Ur the best LOMU Question: With 53 tries from 77 caps, who is the leading try scorer for the Welsh national Rugby Union team? Answer: {'aliases': ['SHANE WILLIAMS', 'Shane Williams', 'Shane Mark Williams'], 'normalized_aliases': ['shane mark williams', 'shane williams'], 'matched_wiki_entity_name': '', 'normalized_matched_wiki_entity_name': '', 'normalized_value': 'shane williams', 'type': 'WikipediaEntity', 'value': 'SHANE WILLIAMS'} Passage: Facts & Figures - Lancashire and Blackpool Facts & Figures Home Media Room Facts & Figures Facts & Figures As befitting a county with a long and fascinating history (and one that continues to thrive and surprise), Lancashire is a facts and figures seeker's paradise. Read on to discover more about the Red Rose county and why it's bursting with 'colour'. Geography and History Lancashire was established in 1183 It has a population of 1,460,893 (2011 Census) The county covers an area of 3,075 sq km - making it one of the largest shire counties It is also surprisingly rural with 80 per cent of the county officially classed as rural Dunsop Bridge in the Ribble Valley is the centre of the British Isles The highest point in the county is Gragareth at 627 metres high or 2057 feet, making it a mountain. It is near Whernside, one of Yorkshire's `Three Peaks` Preston is one of England's newest Cities and in 2012 it celebrated the Preston Guild, which only happens every 20 years and is England's oldest festival The Leeds Liverpool Canal - Britain's longest - flows through large parts of the county The mill towns of Blackburn and Burnley were the birthplace of the Industrial Revolution in the 18th century You can see Blackburn and Burnley from the famous Pendle Hill. The hill is only 165ft shy of also being called a mountain The largely `undiscovered` Forest of Bowland Area of Outstanding Beauty covers 802 square km - making it the same size as New York City And the Forest of Bowland is the first protected area in England to be awarded the European Charter for Sustainable Tourism in Protected Areas, joining just 30 other protected areas across Europe Bashall Town, near Clitheroe, is England's smallest town Did you know? Blackpool Illuminations comprise an amazing one million lamps in various types and styles and cost £2.4 million to stage More multi-million pound lottery winners choose Blackpool as their favourite over any other British destination (source: Camelot) It takes 7 years to paint Blackpool Tower from top to bottom and the tower's lifts travel 3,500 miles every year In her official biography, by Sarah Bradford, the Queen expressed a desire to retire to the Ribble Valley And Morecambe's potted shrimps have a Royal seal of approval Miles Standish, the captain of America's first settlers, the Pilgrim Fathers, came from Chorley Lancaster born scientist Richard Owen created the word `dinosaur` The post office and craft shop in Chipping is the country's oldest continuously trading shop. A shop has been in existence here since the 1600s Garstang was the world's first Fairtrade town And in Garstang in October 2007, the world's biggest hotpot was created to help launch Taste Lancashire 08. It is in the Guinness World Records.  Famous Lancastrians Among those born in Lancashire: Eric Morecambe (Entertainer) Nick Park (creator of Wallace and Gromit) Andrew Flintoff (Cricketer) Sir Tom Finney (Football Player) Richard Arkwright (Invented the Spinning Machine) James Hargreaves (Invented the Spinning Jenny) Alfred Wainwright (Walking Books Creator) Jane Horrocks (Actress) Chris Lowe (Pet Shop Boys) Jon Richardson (Comedian) Famous Lancashire Stonyhurst College and the surrounding Ribble Valley is said to be the inspiration for Tolkien's Middle-earth from `Lord of the Rings` - his son boarded at the college which he visited regularly Pendle Hill is where George Fox is believed to have had his vision in 1640 prior to founding the Quaker Movement The trial of the Pendle Witches in Lancaster in 1612 is the UK's most famous witchhunt and in 2012 Lancashire marked its 400th Centenary Squires Gate, now known as Blackpool International Airport, was the UK's first airport Blackpool's permanent electric street tramway was the world's first when it opened in 1885 Martin Mere, Lancashire's largest lake, is said to be the last known home of King Arthur's sword `Excalibur` Roger Bannister, the first person to break the four minute mile, lived at what is now Pendle Heritage Centre in Barrowford Sirloin beef is said to get its name after a visit by James 1 to Hoghton Tower near Preston, where he enjoyed a piece of beef so much - that he knighted it Tourism statistics There are 75 million visitor days to Lancashire each year In 2014 Lancashire attracted just over 63 million visitors who contributed £3.68 billion to the local economy and helped support 56,074 jobs By 2016 the aim is to attract 85 million visitors, who will help to support 70,000 jobs The Pleasure Beach, Blackpool is one of the UK's top visitor attractions, welcoming over 7.8 million visitors each season The Pepsi Max opened in 1994. At 235ft high it is the tallest rollercoaster in Europe. It is just over a mile in length and reaches 85 mph, making it the fastest roller coaster in Europe (updated August 2015) For more information and inspiration, places to visit and things to do VisitLancashire.com News Question: In terms of population, which is the largest city in Lancashire? Answer: {'aliases': ['PR postcode area', 'PRESTON'], 'normalized_aliases': ['preston', 'pr postcode area'], 'matched_wiki_entity_name': '', 'normalized_matched_wiki_entity_name': '', 'normalized_value': 'preston', 'type': 'WikipediaEntity', 'value': 'PRESTON'}
{ "task_name": "trivia_qa" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.SingleVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ForEachVariableStatement); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); syntaxKindsMissing.Add(SyntaxKind.DiscardDesignation); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.State); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer); diagnosticService.GetDiagnosticDescriptors(projectOpt: null); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(Workspace workspace) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); } private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); } public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } } }
{ "task_name": "lcc" }
//--------------------------------------------------------------------------- // // <copyright file="TransformCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { /// <summary> /// A collection of Transform objects. /// </summary> public sealed partial class TransformCollection : Animatable, IList, IList<Transform> { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new TransformCollection Clone() { return (TransformCollection)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new TransformCollection CloneCurrentValue() { return (TransformCollection)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region IList<T> /// <summary> /// Adds "value" to the list /// </summary> public void Add(Transform value) { AddHelper(value); } /// <summary> /// Removes all elements from the list /// </summary> public void Clear() { WritePreamble(); // As part of Clear()'ing the collection, we will iterate it and call // OnFreezablePropertyChanged and OnRemove for each item. // However, OnRemove assumes that the item to be removed has already been // pulled from the underlying collection. To statisfy this condition, // we store the old collection and clear _collection before we call these methods. // As Clear() semantics do not include TrimToFit behavior, we create the new // collection storage at the same size as the previous. This is to provide // as close as possible the same perf characteristics as less complicated collections. FrugalStructList<Transform> oldCollection = _collection; _collection = new FrugalStructList<Transform>(_collection.Capacity); for (int i = oldCollection.Count - 1; i >= 0; i--) { OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null); // Fire the OnRemove handlers for each item. We're not ensuring that // all OnRemove's get called if a resumable exception is thrown. // At this time, these call-outs are not public, so we do not handle exceptions. OnRemove( /* oldValue */ oldCollection[i]); } ++_version; WritePostscript(); } /// <summary> /// Determines if the list contains "value" /// </summary> public bool Contains(Transform value) { ReadPreamble(); return _collection.Contains(value); } /// <summary> /// Returns the index of "value" in the list /// </summary> public int IndexOf(Transform value) { ReadPreamble(); return _collection.IndexOf(value); } /// <summary> /// Inserts "value" into the list at the specified position /// </summary> public void Insert(int index, Transform value) { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value); _collection.Insert(index, value); OnInsert(value); ++_version; WritePostscript(); } /// <summary> /// Removes "value" from the list /// </summary> public bool Remove(Transform value) { WritePreamble(); // By design collections "succeed silently" if you attempt to remove an item // not in the collection. Therefore we need to first verify the old value exists // before calling OnFreezablePropertyChanged. Since we already need to locate // the item in the collection we keep the index and use RemoveAt(...) to do // the work. (Windows OS #1016178) // We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged // is only called conditionally. IList.IndexOf returns -1 if the value is not found. int index = IndexOf(value); if (index >= 0) { Transform oldValue = _collection[index]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; WritePostscript(); return true; } // Collection_Remove returns true, calls WritePostscript, // increments version, and does UpdateResource if it succeeds return false; } /// <summary> /// Removes the element at the specified index /// </summary> public void RemoveAt(int index) { RemoveAtWithoutFiringPublicEvents(index); // RemoveAtWithoutFiringPublicEvents incremented the version WritePostscript(); } /// <summary> /// Removes the element at the specified index without firing /// the public Changed event. /// The caller - typically a public method - is responsible for calling /// WritePostscript if appropriate. /// </summary> internal void RemoveAtWithoutFiringPublicEvents(int index) { WritePreamble(); Transform oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; // No WritePostScript to avoid firing the Changed event. } /// <summary> /// Indexer for the collection /// </summary> public Transform this[int index] { get { ReadPreamble(); return _collection[index]; } set { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); if (!Object.ReferenceEquals(_collection[ index ], value)) { Transform oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, value); _collection[ index ] = value; OnSet(oldValue, value); } ++_version; WritePostscript(); } } #endregion #region ICollection<T> /// <summary> /// The number of elements contained in the collection. /// </summary> public int Count { get { ReadPreamble(); return _collection.Count; } } /// <summary> /// Copies the elements of the collection into "array" starting at "index" /// </summary> public void CopyTo(Transform[] array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } _collection.CopyTo(array, index); } bool ICollection<Transform>.IsReadOnly { get { ReadPreamble(); return IsFrozen; } } #endregion #region IEnumerable<T> /// <summary> /// Returns an enumerator for the collection /// </summary> public Enumerator GetEnumerator() { ReadPreamble(); return new Enumerator(this); } IEnumerator<Transform> IEnumerable<Transform>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IList bool IList.IsReadOnly { get { return ((ICollection<Transform>)this).IsReadOnly; } } bool IList.IsFixedSize { get { ReadPreamble(); return IsFrozen; } } object IList.this[int index] { get { return this[index]; } set { // Forwards to typed implementation this[index] = Cast(value); } } int IList.Add(object value) { // Forward to typed helper return AddHelper(Cast(value)); } bool IList.Contains(object value) { return Contains(value as Transform); } int IList.IndexOf(object value) { return IndexOf(value as Transform); } void IList.Insert(int index, object value) { // Forward to IList<T> Insert Insert(index, Cast(value)); } void IList.Remove(object value) { Remove(value as Transform); } #endregion #region ICollection void ICollection.CopyTo(Array array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } if (array.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank)); } // Elsewhere in the collection we throw an AE when the type is // bad so we do it here as well to be consistent try { int count = _collection.Count; for (int i = 0; i < count; i++) { array.SetValue(_collection[i], index + i); } } catch (InvalidCastException e) { throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e); } } bool ICollection.IsSynchronized { get { ReadPreamble(); return IsFrozen || Dispatcher != null; } } object ICollection.SyncRoot { get { ReadPreamble(); return this; } } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Internal Helpers /// <summary> /// A frozen empty TransformCollection. /// </summary> internal static TransformCollection Empty { get { if (s_empty == null) { TransformCollection collection = new TransformCollection(); collection.Freeze(); s_empty = collection; } return s_empty; } } /// <summary> /// Helper to return read only access. /// </summary> internal Transform Internal_GetItem(int i) { return _collection[i]; } /// <summary> /// Freezable collections need to notify their contained Freezables /// about the change in the InheritanceContext /// </summary> internal override void OnInheritanceContextChangedCore(EventArgs args) { base.OnInheritanceContextChangedCore(args); for (int i=0; i<this.Count; i++) { DependencyObject inheritanceChild = _collection[i]; if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this) { inheritanceChild.OnInheritanceContextChanged(args); } } } #endregion #region Private Helpers private Transform Cast(object value) { if( value == null ) { throw new System.ArgumentNullException("value"); } if (!(value is Transform)) { throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Transform")); } return (Transform) value; } // IList.Add returns int and IList<T>.Add does not. This // is called by both Adds and IList<T>'s just ignores the // integer private int AddHelper(Transform value) { int index = AddWithoutFiringPublicEvents(value); // AddAtWithoutFiringPublicEvents incremented the version WritePostscript(); return index; } internal int AddWithoutFiringPublicEvents(Transform value) { int index = -1; if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); Transform newValue = value; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); index = _collection.Add(newValue); OnInsert(newValue); ++_version; // No WritePostScript to avoid firing the Changed event. return index; } internal event ItemInsertedHandler ItemInserted; internal event ItemRemovedHandler ItemRemoved; private void OnInsert(object item) { if (ItemInserted != null) { ItemInserted(this, item); } } private void OnRemove(object oldValue) { if (ItemRemoved != null) { ItemRemoved(this, oldValue); } } private void OnSet(object oldValue, object newValue) { OnInsert(newValue); OnRemove(oldValue); } #endregion Private Helpers private static TransformCollection s_empty; #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new TransformCollection(); } /// <summary> /// Implementation of Freezable.CloneCore() /// </summary> protected override void CloneCore(Freezable source) { TransformCollection sourceTransformCollection = (TransformCollection) source; base.CloneCore(source); int count = sourceTransformCollection._collection.Count; _collection = new FrugalStructList<Transform>(count); for (int i = 0; i < count; i++) { Transform newValue = (Transform) sourceTransformCollection._collection[i].Clone(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.CloneCurrentValueCore() /// </summary> protected override void CloneCurrentValueCore(Freezable source) { TransformCollection sourceTransformCollection = (TransformCollection) source; base.CloneCurrentValueCore(source); int count = sourceTransformCollection._collection.Count; _collection = new FrugalStructList<Transform>(count); for (int i = 0; i < count; i++) { Transform newValue = (Transform) sourceTransformCollection._collection[i].CloneCurrentValue(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetAsFrozenCore() /// </summary> protected override void GetAsFrozenCore(Freezable source) { TransformCollection sourceTransformCollection = (TransformCollection) source; base.GetAsFrozenCore(source); int count = sourceTransformCollection._collection.Count; _collection = new FrugalStructList<Transform>(count); for (int i = 0; i < count; i++) { Transform newValue = (Transform) sourceTransformCollection._collection[i].GetAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetCurrentValueAsFrozenCore() /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { TransformCollection sourceTransformCollection = (TransformCollection) source; base.GetCurrentValueAsFrozenCore(source); int count = sourceTransformCollection._collection.Count; _collection = new FrugalStructList<Transform>(count); for (int i = 0; i < count; i++) { Transform newValue = (Transform) sourceTransformCollection._collection[i].GetCurrentValueAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); int count = _collection.Count; for (int i = 0; i < count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_collection[i], isChecking); } return canFreeze; } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal FrugalStructList<Transform> _collection; internal uint _version = 0; #endregion Internal Fields #region Enumerator /// <summary> /// Enumerates the items in a TransformCollection /// </summary> public struct Enumerator : IEnumerator, IEnumerator<Transform> { #region Constructor internal Enumerator(TransformCollection list) { Debug.Assert(list != null, "list may not be null."); _list = list; _version = list._version; _index = -1; _current = default(Transform); } #endregion #region Methods void IDisposable.Dispose() { } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element, /// false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { _list.ReadPreamble(); if (_version == _list._version) { if (_index > -2 && _index < _list._collection.Count - 1) { _current = _list._collection[++_index]; return true; } else { _index = -2; // -2 indicates "past the end" return false; } } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } /// <summary> /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// </summary> public void Reset() { _list.ReadPreamble(); if (_version == _list._version) { _index = -1; } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } #endregion #region Properties object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Current element /// /// The behavior of IEnumerable&lt;T>.Current is undefined /// before the first MoveNext and after we have walked /// off the end of the list. However, the IEnumerable.Current /// contract requires that we throw exceptions /// </summary> public Transform Current { get { if (_index > -1) { return _current; } else if (_index == -1) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted)); } else { Debug.Assert(_index == -2, "expected -2, got " + _index + "\n"); throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd)); } } } #endregion #region Data private Transform _current; private TransformCollection _list; private uint _version; private int _index; #endregion } #endregion #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Initializes a new instance that is empty. /// </summary> public TransformCollection() { _collection = new FrugalStructList<Transform>(); } /// <summary> /// Initializes a new instance that is empty and has the specified initial capacity. /// </summary> /// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param> public TransformCollection(int capacity) { _collection = new FrugalStructList<Transform>(capacity); } /// <summary> /// Creates a TransformCollection with all of the same elements as collection /// </summary> public TransformCollection(IEnumerable<Transform> collection) { // The WritePreamble and WritePostscript aren't technically necessary // in the constructor as of 1/20/05 but they are put here in case // their behavior changes at a later date WritePreamble(); if (collection != null) { bool needsItemValidation = true; ICollection<Transform> icollectionOfT = collection as ICollection<Transform>; if (icollectionOfT != null) { _collection = new FrugalStructList<Transform>(icollectionOfT); } else { ICollection icollection = collection as ICollection; if (icollection != null) // an IC but not and IC<T> { _collection = new FrugalStructList<Transform>(icollection); } else // not a IC or IC<T> so fall back to the slower Add { _collection = new FrugalStructList<Transform>(); foreach (Transform item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } Transform newValue = item; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } needsItemValidation = false; } } if (needsItemValidation) { foreach (Transform item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } OnFreezablePropertyChanged(/* oldValue = */ null, item); OnInsert(item); } } WritePostscript(); } else { throw new ArgumentNullException("collection"); } } #endregion Constructors } }
{ "task_name": "lcc" }
Passage 1: Harry Wainwright (footballer) Harry Wainwright( born 1899; date of death unknown) was an English footballer. Passage 2: Thomas Scott (diver) Thomas Scott( 1907- date of death unknown) was an English diver. Passage 3: Etan Boritzer Etan Boritzer( born 1950) is an American writer of children ’s literature who is best known for his book" What is God?" first published in 1989. His best selling" What is?" illustrated children's book series on character education and difficult subjects for children is a popular teaching guide for parents, teachers and child- life professionals. Boritzer gained national critical acclaim after" What is God?" was published in 1989 although the book has caused controversy from religious fundamentalists for its universalist views. The other current books in the" What is?" series include What is Love?, What is Death?, What is Beautiful?, What is Funny?, What is Right?, What is Peace?, What is Money?, What is Dreaming?, What is a Friend?, What is True?, What is a Family?, What is a Feeling?" The series is now also translated into 15 languages. Boritzer was first published in 1963 at the age of 13 when he wrote an essay in his English class at Wade Junior High School in the Bronx, New York on the assassination of John F. Kennedy. His essay was included in a special anthology by New York City public school children compiled and published by the New York City Department of Education. Boritzer now lives in Venice, California and maintains his publishing office there also. He has helped numerous other authors to get published through" How to Get Your Book Published!" programs. Boritzer is also a yoga teacher who teaches regular classes locally and guest- teaches nationally. He is also recognized nationally as an erudite speaker on" The Teachings of the Buddha." Passage 4: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 5: Salil Dutta Salil Dutta (1932 – 20 September 2004) was a Bengali director, screenwriter and actor. Passage 6: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 7: Albert Thompson (footballer, born 1912) Albert Thompson( born 1912, date of death unknown) was a Welsh footballer. Passage 8: Theodred II (Bishop of Elmham) Theodred II was a medieval Bishop of Elmham. The date of Theodred's consecration unknown, but the date of his death was sometime between 995 and 997. Passage 9: Surya Sikha Surya Sikha is a Bengali romance drama film directed by Salil Dutta. This film was released on 12 July 1963 in the banner of Chhayachhabi Pratisthan. Passage 10: Bill Smith (footballer, born 1897) William Thomas Smith( born 9 April 1897, date of death unknown) was an English professional footballer. Question: When did the director of film Surya Sikha die? Answer: 20 September 2004
{ "task_name": "2WikiMultihopQA" }
Document: FILE - In this Sept. 17, 2016, file photo, Ohio State head coach Urban Meyer, right, and then-assistant coach Zach Smith, left, gesture from the sidelines during an NCAA college football game against... (Associated Press) FILE - In this Sept. 17, 2016, file photo, Ohio State head coach Urban Meyer, right, and then-assistant coach Zach Smith, left, gesture from the sidelines during an NCAA college football game against Oklahoma in Norman, Okla. Ohio State expects to open fall camp as scheduled on Friday, Aug. 3, 2018,... (Associated Press) Urban Meyer is insisting that he properly handled 2015 allegations of domestic violence against one of his assistant coaches at the time, though he acknowledged he was not forthright with reporters when questioned last week about the claims. The assistant Meyer fired, Zach Smith, also spoke up on Friday, denying that he abused his ex-wife, backing his former boss and placing Ohio State's athletic director into the middle of the picture. Two days after Ohio State sidelined Meyer and opened an investigation into what its superstar coach knew and did about accusations of abuse made against Smith by his ex-wife, two central figures in this college football drama answered some questions — and left much to be explained. Meyer posted a statement addressed to Buckeyes fans on Twitter not long after his team, expected to be one of the best in the nation, opened practice for the upcoming season without him. Meyer was put on paid administrative leave Wednesday. While Meyer's statement was still being digested, Smith went on Columbus radio station 105.7 The Zone. In the interview , Smith said Ohio State athletic director Gene Smith questioned him during the 2015 football season about the allegations made by Courtney Smith that fall. Police reports were made about two separate incidents, but Zach Smith has never been criminally charged. Zach Smith was fired last week by Meyer, a few days after his wife obtained a protective order against him. Smith also did an interview with ESPN. He said he never assaulted his wife and any physical injuries she might have suffered were the result of him defending himself. He said Gene Smith was alerted by police about the 2015 allegations. Zach Smith said that after speaking to Gene Smith about them, he spoke to Meyer. He said Meyer told him then that he would fire Smith if the head coach found out Smith hit his wife. "I don't know what else Urban Meyer could have done," Zach Smith told ESPN. The crisis at one of the most storied programs in college football history comes as the school is reeling from a sexual abuse scandal involving a now-dead sports doctor, Richard Strauss. The Buckeyes open the season at home Sept. 1 against Oregon State. Co-offensive coordinator Ryan Day is acting head coach and there is no timetable for the Meyer inquiry to conclude. "Over the past several days I have been portrayed as being indifferent to domestic violence and as someone who did not take appropriate action when warranted," Meyer said. "Here is the truth: While at the University of Florida and now at the Ohio State University I have always followed proper reporting protocols and procedures when I have learned of an incident involving a student-athlete, coach or member of our staff by elevating the issues to the proper channels. And I did so regarding the Zach Smith incident in 2015. I take that responsibility very seriously and any suggestion to the contrary is simply false." At Big Ten media days last week, Meyer said he knew of an incident involving the Smiths in 2009 and that he and his wife, Shelley Meyer, addressed it with the Smiths. He was also asked about a 2015 incident alleged by Courtney Smith, who said she told Meyer's wife about those incidents. "I can't say it didn't happen because I wasn't there," Meyer said at the time. "I was never told about anything and nothing ever came to light. I've never had a conversation about it. I know nothing about it. First I heard about that was last night. No, and I asked some people back at the office to call and say what happened and they came back and said they know nothing about it." Meyer said his intention at media day was not to say anything inaccurate. "However, I was not adequately prepared to discuss these sensitive personnel issues with the media, and I apologize for the way I handled those questions," he said. Meyer said he will fully cooperate with investigators. Ohio State did not respond Friday to a request seeking comment on the comments by Meyer or Smith, who told the radio station his marriage was volatile and that he made mistakes. The Smiths divorced in 2016. "I don't believe I have ever threatened her or anyone," Zach Smith, who had been an assistant at Ohio State since Meyer was hired in 2012, said in the radio interview. Smith, the grandson of late Buckeyes coach Earle Bruce, a mentor to Meyer, played for Meyer when he was coach at Bowling Green in 2001-02. Smith also was a graduate assistant for Meyer at Florida for five seasons. In 2009, Zach Smith was accused by his wife of assault, but charges were not filed. Meyer has said he and his wife, Shelley, counseled the couple at the time. Courtney Smith has also said she told Shelley Meyer about the 2015 incidents and shared pictures of injuries through text messages that she shared with college football reporter Brett McMurphy . In one text to Courtney Smith, Shelley Meyer said of Zach Smith: "He scares me." Meyer has been at Ohio State for six seasons, going 73-8 with a national championship in 2014 and two Big Ten conference titles. He earlier won two national titles at Florida. Ohio State's policy on sexual misconduct says anyone who supervises faculty, staff, students or volunteers has a duty to report "when they receive a disclosure of sexual misconduct or become aware of information that would lead a reasonable person to believe that sexual misconduct may have occurred involving anyone covered under this policy." A clause in Meyer's new contract, which raised his salary to $7.6 million this year and runs through 2022, also requires him to "report to Ohio State's Title IX athletics any known violations" of the sexual misconduct policy involving students, faculty or staff at the risk of being fired with cause. Firing Meyer without cause would cost Ohio State a nearly $40 million buyout. ___ Follow Ralph D. Russo at www.Twitter.com/ralphDrussoAP and listen on https://itunes.apple.com/us/podcast/ap-top-25-college-football-podcast/id1138957862?mt=2 ___ More AP college football: https://collegefootball.ap.org and https://twitter.com/AP_Top25 Summary: – Urban Meyer is insisting that he properly handled 2015 allegations of domestic violence against one of his assistant coaches at the time, though he acknowledged he was not forthright with reporters when questioned last week about the claims, the AP reports. The assistant Meyer fired, Zach Smith, also spoke up on Friday, denying that he abused his ex-wife, backing his former boss and placing Ohio State's athletic director into the middle of the picture. Two days after Ohio State sidelined Meyer and opened an investigation into what its superstar coach knew and did about accusations of abuse made against Smith by his ex-wife, two central figures in this college football drama answered some questions—and left much to be explained. Meyer posted a statement addressed to Buckeyes fans on Twitter not long after his team, expected to be one of the best in the nation, opened practice for the upcoming season without him. "Here is the truth: While at the University of Florida and now at the Ohio State University I have always followed proper reporting protocols and procedures when I have learned of an incident involving a student-athlete, coach or member of our staff by elevating the issues to the proper channels," he writes. "And I did so regarding the Zach Smith incident in 2015." Zach Smith was fired last week by Meyer, a few days after his wife obtained a protective order against him. Meyer was put on paid administrative leave Wednesday.
{ "task_name": "multi_news" }
namespace CarCtrl { partial class formCtrl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formCtrl)); this.panelButtons = new System.Windows.Forms.Panel(); this.btRight = new System.Windows.Forms.Panel(); this.lbRight = new System.Windows.Forms.Label(); this.btDown = new System.Windows.Forms.Panel(); this.lbDown = new System.Windows.Forms.Label(); this.btLeft = new System.Windows.Forms.Panel(); this.lbLeft = new System.Windows.Forms.Label(); this.btUp = new System.Windows.Forms.Panel(); this.lbUp = new System.Windows.Forms.Label(); this.mmLog = new System.Windows.Forms.TextBox(); this.lbCmdLog = new System.Windows.Forms.Label(); this.lbSerial = new System.Windows.Forms.Label(); this.cbbSerialPort = new System.Windows.Forms.ComboBox(); this.lbBitSend = new System.Windows.Forms.Label(); this.edtBitSync = new System.Windows.Forms.NumericUpDown(); this.edtPacketSync = new System.Windows.Forms.NumericUpDown(); this.lbPacketSend = new System.Windows.Forms.Label(); this.btStartStop = new System.Windows.Forms.Button(); this.mmStatus = new System.Windows.Forms.TextBox(); this.lbPortStat = new System.Windows.Forms.Label(); this.timerLog = new System.Windows.Forms.Timer(this.components); this.lbSent = new System.Windows.Forms.Label(); this.panelButtons.SuspendLayout(); this.btRight.SuspendLayout(); this.btDown.SuspendLayout(); this.btLeft.SuspendLayout(); this.btUp.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.edtBitSync)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.edtPacketSync)).BeginInit(); this.SuspendLayout(); // // panelButtons // this.panelButtons.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panelButtons.Controls.Add(this.btRight); this.panelButtons.Controls.Add(this.btDown); this.panelButtons.Controls.Add(this.btLeft); this.panelButtons.Controls.Add(this.btUp); this.panelButtons.Location = new System.Drawing.Point(271, 225); this.panelButtons.Name = "panelButtons"; this.panelButtons.Size = new System.Drawing.Size(192, 187); this.panelButtons.TabIndex = 0; // // btRight // this.btRight.BackColor = System.Drawing.Color.Gray; this.btRight.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btRight.Controls.Add(this.lbRight); this.btRight.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btRight.Location = new System.Drawing.Point(125, 63); this.btRight.Name = "btRight"; this.btRight.Size = new System.Drawing.Size(60, 60); this.btRight.TabIndex = 3; // // lbRight // this.lbRight.Dock = System.Windows.Forms.DockStyle.Fill; this.lbRight.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbRight.Location = new System.Drawing.Point(0, 0); this.lbRight.Name = "lbRight"; this.lbRight.Size = new System.Drawing.Size(58, 58); this.lbRight.TabIndex = 1; this.lbRight.Text = "4"; this.lbRight.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btDown // this.btDown.BackColor = System.Drawing.Color.Gray; this.btDown.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btDown.Controls.Add(this.lbDown); this.btDown.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btDown.Location = new System.Drawing.Point(65, 123); this.btDown.Name = "btDown"; this.btDown.Size = new System.Drawing.Size(60, 60); this.btDown.TabIndex = 2; // // lbDown // this.lbDown.Dock = System.Windows.Forms.DockStyle.Fill; this.lbDown.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbDown.Location = new System.Drawing.Point(0, 0); this.lbDown.Name = "lbDown"; this.lbDown.Size = new System.Drawing.Size(58, 58); this.lbDown.TabIndex = 1; this.lbDown.Text = "6"; this.lbDown.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btLeft // this.btLeft.BackColor = System.Drawing.Color.Gray; this.btLeft.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btLeft.Controls.Add(this.lbLeft); this.btLeft.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btLeft.Location = new System.Drawing.Point(5, 63); this.btLeft.Name = "btLeft"; this.btLeft.Size = new System.Drawing.Size(60, 60); this.btLeft.TabIndex = 2; // // lbLeft // this.lbLeft.Dock = System.Windows.Forms.DockStyle.Fill; this.lbLeft.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbLeft.Location = new System.Drawing.Point(0, 0); this.lbLeft.Name = "lbLeft"; this.lbLeft.Size = new System.Drawing.Size(58, 58); this.lbLeft.TabIndex = 1; this.lbLeft.Text = "3"; this.lbLeft.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btUp // this.btUp.BackColor = System.Drawing.Color.Gray; this.btUp.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.btUp.Controls.Add(this.lbUp); this.btUp.Font = new System.Drawing.Font("Webdings", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.btUp.Location = new System.Drawing.Point(65, 3); this.btUp.Name = "btUp"; this.btUp.Size = new System.Drawing.Size(60, 60); this.btUp.TabIndex = 1; // // lbUp // this.lbUp.Dock = System.Windows.Forms.DockStyle.Fill; this.lbUp.Font = new System.Drawing.Font("Webdings", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.lbUp.Location = new System.Drawing.Point(0, 0); this.lbUp.Name = "lbUp"; this.lbUp.Size = new System.Drawing.Size(58, 58); this.lbUp.TabIndex = 0; this.lbUp.Text = "5"; this.lbUp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // mmLog // this.mmLog.Location = new System.Drawing.Point(5, 20); this.mmLog.Multiline = true; this.mmLog.Name = "mmLog"; this.mmLog.ReadOnly = true; this.mmLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.mmLog.Size = new System.Drawing.Size(325, 167); this.mmLog.TabIndex = 1; this.mmLog.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.mmLog.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // lbCmdLog // this.lbCmdLog.AutoSize = true; this.lbCmdLog.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lbCmdLog.Location = new System.Drawing.Point(2, 4); this.lbCmdLog.Name = "lbCmdLog"; this.lbCmdLog.Size = new System.Drawing.Size(90, 13); this.lbCmdLog.TabIndex = 2; this.lbCmdLog.Text = "Command Log:"; // // lbSerial // this.lbSerial.AutoSize = true; this.lbSerial.Location = new System.Drawing.Point(2, 225); this.lbSerial.Name = "lbSerial"; this.lbSerial.Size = new System.Drawing.Size(58, 13); this.lbSerial.TabIndex = 3; this.lbSerial.Text = "Serial Port:"; // // cbbSerialPort // this.cbbSerialPort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbbSerialPort.FormattingEnabled = true; this.cbbSerialPort.Location = new System.Drawing.Point(5, 241); this.cbbSerialPort.Name = "cbbSerialPort"; this.cbbSerialPort.Size = new System.Drawing.Size(136, 21); this.cbbSerialPort.TabIndex = 4; // // lbBitSend // this.lbBitSend.AutoSize = true; this.lbBitSend.Location = new System.Drawing.Point(2, 267); this.lbBitSend.Name = "lbBitSend"; this.lbBitSend.Size = new System.Drawing.Size(76, 13); this.lbBitSend.TabIndex = 5; this.lbBitSend.Text = "Bit Sync Delay"; // // edtBitSync // this.edtBitSync.Location = new System.Drawing.Point(5, 283); this.edtBitSync.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.edtBitSync.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.edtBitSync.Name = "edtBitSync"; this.edtBitSync.Size = new System.Drawing.Size(136, 20); this.edtBitSync.TabIndex = 6; this.edtBitSync.Value = new decimal(new int[] { 50, 0, 0, 0}); // // edtPacketSync // this.edtPacketSync.Location = new System.Drawing.Point(5, 324); this.edtPacketSync.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.edtPacketSync.Minimum = new decimal(new int[] { 20, 0, 0, 0}); this.edtPacketSync.Name = "edtPacketSync"; this.edtPacketSync.Size = new System.Drawing.Size(136, 20); this.edtPacketSync.TabIndex = 8; this.edtPacketSync.Value = new decimal(new int[] { 300, 0, 0, 0}); // // lbPacketSend // this.lbPacketSend.AutoSize = true; this.lbPacketSend.Location = new System.Drawing.Point(2, 308); this.lbPacketSend.Name = "lbPacketSend"; this.lbPacketSend.Size = new System.Drawing.Size(98, 13); this.lbPacketSend.TabIndex = 7; this.lbPacketSend.Text = "Packet Sync Delay"; // // btStartStop // this.btStartStop.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btStartStop.Location = new System.Drawing.Point(5, 389); this.btStartStop.Name = "btStartStop"; this.btStartStop.Size = new System.Drawing.Size(75, 23); this.btStartStop.TabIndex = 9; this.btStartStop.Text = "Start"; this.btStartStop.UseVisualStyleBackColor = true; this.btStartStop.Click += new System.EventHandler(this.btStartStop_Click); this.btStartStop.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.btStartStop.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // mmStatus // this.mmStatus.Cursor = System.Windows.Forms.Cursors.Arrow; this.mmStatus.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.mmStatus.Location = new System.Drawing.Point(336, 20); this.mmStatus.Multiline = true; this.mmStatus.Name = "mmStatus"; this.mmStatus.ReadOnly = true; this.mmStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.mmStatus.Size = new System.Drawing.Size(127, 167); this.mmStatus.TabIndex = 10; this.mmStatus.WordWrap = false; this.mmStatus.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.mmStatus.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); // // lbPortStat // this.lbPortStat.AutoSize = true; this.lbPortStat.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lbPortStat.Location = new System.Drawing.Point(335, 6); this.lbPortStat.Name = "lbPortStat"; this.lbPortStat.Size = new System.Drawing.Size(110, 13); this.lbPortStat.TabIndex = 11; this.lbPortStat.Text = "DTR RTS STAT"; // // timerLog // this.timerLog.Enabled = true; this.timerLog.Interval = 50; this.timerLog.Tick += new System.EventHandler(this.timerLog_Tick); // // lbSent // this.lbSent.AutoSize = true; this.lbSent.Location = new System.Drawing.Point(335, 190); this.lbSent.Name = "lbSent"; this.lbSent.Size = new System.Drawing.Size(61, 13); this.lbSent.TabIndex = 12; this.lbSent.Text = "Bits Sent: 0"; // // formCtrl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(468, 416); this.Controls.Add(this.lbSent); this.Controls.Add(this.lbPortStat); this.Controls.Add(this.mmStatus); this.Controls.Add(this.btStartStop); this.Controls.Add(this.edtPacketSync); this.Controls.Add(this.lbPacketSend); this.Controls.Add(this.edtBitSync); this.Controls.Add(this.lbBitSend); this.Controls.Add(this.cbbSerialPort); this.Controls.Add(this.lbSerial); this.Controls.Add(this.lbCmdLog); this.Controls.Add(this.mmLog); this.Controls.Add(this.panelButtons); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "formCtrl"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Car Control"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.formCtrl_FormClosing); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.lb_KeyUp); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lb_KeyDown); this.panelButtons.ResumeLayout(false); this.btRight.ResumeLayout(false); this.btDown.ResumeLayout(false); this.btLeft.ResumeLayout(false); this.btUp.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.edtBitSync)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.edtPacketSync)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panelButtons; private System.Windows.Forms.Panel btRight; private System.Windows.Forms.Panel btDown; private System.Windows.Forms.Panel btLeft; private System.Windows.Forms.Panel btUp; private System.Windows.Forms.Label lbRight; private System.Windows.Forms.Label lbDown; private System.Windows.Forms.Label lbLeft; private System.Windows.Forms.Label lbUp; private System.Windows.Forms.TextBox mmLog; private System.Windows.Forms.Label lbCmdLog; private System.Windows.Forms.Label lbSerial; private System.Windows.Forms.ComboBox cbbSerialPort; private System.Windows.Forms.Label lbBitSend; private System.Windows.Forms.NumericUpDown edtBitSync; private System.Windows.Forms.NumericUpDown edtPacketSync; private System.Windows.Forms.Label lbPacketSend; private System.Windows.Forms.Button btStartStop; private System.Windows.Forms.TextBox mmStatus; private System.Windows.Forms.Label lbPortStat; private System.Windows.Forms.Timer timerLog; private System.Windows.Forms.Label lbSent; } }
{ "task_name": "lcc" }
Passage 1: Lars Eliasson He is the father of the later Member of Parliament Anna Eliasson. Passage 2: V. Ravichandran Veeraswamy Ravichandran, known simply as Dr. Ravichandran, is an Indian actor and filmmaker in Kannada cinema, known for his multi-faceted works in his associated films. Son of notable film producer N. Veeraswamy, Dr. Ravichandran made his acting debut in "Khadeema Kallaru" (1982) as an antagonist and followed it up with "Chakravyuha" in 1983. After starring in a series of multi-starrers in supporting and lead roles, he cast himself in his directorial debut "Premaloka" (1987), which became one of the highest grossing blockbuster films in Kannada cinema. As a producer, he continues to run "Sri Eswari Productions". Passage 3: Chinna (1994 film) Chinna is a 1994 Kannada action film produced, written, directed and enacted by V. Ravichandran. The rest of the cast includes Yamuna, Puneet Issar, Mukhyamantri Chandru, Lokanath, Pandari Bai amongst others. Ravichandran plays the role of a cop happily settled with his wife and suddenly comes to know about his ancestral property existence in the middle of a forest occupied by the local goons. This is the only Kannada Film of Sabu Cyril who is an acclaimed National Award winning art director. The music was composed by Hamsalekha and was declared a musical hit upon release. Passage 4: Yasuichi Oshima He is the father of manga artist Towa Oshima. Passage 5: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 6: Peter Hamel Peter Hamel( 1911–1979) was a German screenwriter and a director of film and television. He appeared as himself in the 1948 comedy" Film Without a Title". He is the father of the composer Peter Michael Hamel. Passage 7: Obata Toramori He was the father of Obata Masamori. Passage 8: Paul Brooke Paul Brooke( born 22 November 1944) is a retired English actor of film, television and radio. He is the father of actor Tom Brooke. Passage 9: Inoue Masaru (bureaucrat) Viscount was the first Director of Railways in Japan and is known as the" father of the Japanese railways". Passage 10: Cleomenes II Cleomenes II( died 309 BC) was Agiad King of Sparta from 369 to 309 BC. The son of Cleombrotus I, he succeeded his brother Agesipolis II. He was the father of Acrotatus I, the father of Areus I, and of Cleonymus, the father of Leonidas II. Question: Who is the father of the director of film Chinna (1994 Film)? Answer: N. Veeraswamy
{ "task_name": "2WikiMultihopQA" }
Passage 1: Lamman Rucker Lamman Rucker( born October 6, 1971) is an American actor. Rucker began his career on the daytime soap operas" As the World Turns" and" All My Children", before roles in Tyler Perry's films " Why Did I Get Married? Why Did I Get Married Too?", and" Meet the Browns", and its television adaptation. In 2016, he began starring as Jacob Greenleaf in the Oprah Winfrey Network drama series," Greenleaf". Passage 2: John Lennon John Winston Ono Lennon (born John Winston Lennon, 9 October 19408 December 1980) was an English singer, songwriter and peace activist who gained worldwide fame as the founder, co-lead vocalist, and rhythm guitarist of the Beatles. His songwriting partnership with Paul McCartney remains the most successful in history. In 1969, he started the Plastic Ono Band with his second wife, Yoko Ono. After the Beatles disbanded in 1970, Lennon continued as a solo artist. Born in Liverpool, Lennon became involved in the skiffle craze as a teenager. In 1957, he formed his first band, the Quarrymen, which evolved into the Beatles in 1960. He was initially the group's de facto leader, a role gradually ceded to McCartney. Starting in 1967, Lennon's lyrics began to espouse a pacifist message, and some of his songs were soon adopted as anthems by the anti-war movement and the larger counterculture. From 1968 to 1972, he produced more than a dozen records with Ono, including a trilogy of avant-garde albums, his first solo LP "John Lennon/Plastic Ono Band", and the international top 10 singles "Give Peace a ChanceInstant Karma!Imagine" and "Happy Xmas (War Is Over)". Lennon was known for the rebellious nature and acerbic wit in his music, writing, drawings, on film and in interviews. He was controversial through his political and peace activism. After moving to New York City in 1971, his criticism of the Vietnam War resulted in a three-year attempt by the Nixon administration to deport him. In 1975, Lennon disengaged from the music business to raise his infant son Sean, and in 1980, returned with the Ono collaboration "Double Fantasy". He was shot and killed in the archway of his Manhattan apartment building three weeks after the album's release. By 2018, Lennon's solo equivalent album sales had exceeded 72 million units worldwide. In 2002, Lennon was voted eighth in a BBC poll of the 100 Greatest Britons, and in 2008, "Rolling Stone" ranked him the fifth-greatest singer of all time. In 1987, he was inducted into the Songwriters Hall of Fame. Lennon was inducted into the Rock and Roll Hall of Fame twice, as a member of the Beatles in 1988 and as a solo artist in 1994. Passage 3: Billy Milano Billy Milano is a Bronx- born heavy metal musician now based in Austin, Texas. He is the singer and- occasionally- guitarist and bassist of crossover thrash band M.O.D., and he was also the singer of its predecessor, Stormtroopers of Death. He was also the singer of United Forces, which also featured his Stormtroopers of Death bandmate Dan Lilker. Passage 4: It's So Hard "It's So Hard" is a song written and performed by John Lennon which first appeared on his 1971 album "Imagine". Shortly after the album's release, the song was released as the B-side to the single "Imagine. " In Mexico it was released on an EP with "Imagine, Oh My Love" and "Gimme Some Truth. " In 1986, a live performance from 30 August 1972 was released on Lennon's live album "Live in New York City". Passage 5: Caspar Babypants Caspar Babypants is the stage name of children's music artist Chris Ballew, who is also widely known as the singer of The Presidents of the United States of America. Passage 6: O Valencia! " O Valencia!" is the fifth single by the indie rock band The Decemberists, and the first released from their fourth studio album," The Crane Wife". The music was written by The Decemberists and the lyrics by Colin Meloy. It tells a story of two star- crossed lovers. The singer falls in love with a person who belongs to an opposing gang. At the end of the song, the singer's lover jumps in to defend the singer, who is confronting his lover's brother( the singer's" sworn enemy") and is killed by the bullet intended for the singer. Passage 7: G. C. Cameron George Curtis Cameron( born September 21, 1945, in McCall Creek, Mississippi) is an American soul and R&B singer whose currently married to International Recording Artist Linda Dixon Cameron aka “ Lady L. ”. Perhaps best known as the lead singer of supergroup" The Spinners" on their 1970 hit" It's a Shame" and for his 1975 hit" It's So Hard to Say Goodbye to Yesterday". G.C. is credited with having" six different voices." Passage 8: Bernie Bonvoisin Bernard Bonvoisin, known as Bernie Bonvoisin( born 9 July 1956 in Nanterre, Hauts- de- Seine), is a French hard rock singer and film director. He is best known for having been the singer of Trust. He was one of the best friends of Bon Scott the singer of AC/ DC and together they recorded the song" Ride On" which was one of the last songs by Bon Scott. Passage 9: It's So Hard to Say Goodbye to Yesterday " It's So Hard to Say Goodbye to Yesterday" is an R&B song written by Motown husband- and- wife songwriting team Freddie Perren and Christine Yarian for the 1975 film" Cooley High". In the film, the song is performed by Motown artist G.C. Cameron, whose rendition peaked at number 38 on the" Billboard" R&B singles chart that same year. Perren also composed the instrumental score for" Cooley High", and the B-side to" It's So Hard to Say Goodbye to Yesterday" features two of his score compositions from the film. Passage 10: Richard T. Jones Richard Timothy Jones( born January 16, 1972) is an American actor. Jones is best known for his portrayals of Laveinio in the dramatic film" The Wood"( 1999) and Mike of the dramatic films" Why Did I Get Married?"( 2007) and" Why Did I Get Married Too?"( 2010). He is also well known for his role as Bruce Van Exel, court services officer on the CBS television series" Judging Amy" that aired from 1999 to 2005. Question: Why did the performer of song It'S So Hard die? Answer: shot
{ "task_name": "2WikiMultihopQA" }
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package org.springside.modules.utils.concurrent.jsr166e; /** * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/CountedCompleter.java 1.31 * * A {@link ForkJoinTask} with a completion action performed when * triggered and there are no remaining pending actions. * CountedCompleters are in general more robust in the * presence of subtask stalls and blockage than are other forms of * ForkJoinTasks, but are less intuitive to program. Uses of * CountedCompleter are similar to those of other completion based * components (such as {@link java.nio.channels.CompletionHandler}) * except that multiple <em>pending</em> completions may be necessary * to trigger the completion action {@link #onCompletion(CountedCompleter)}, * not just one. * Unless initialized otherwise, the {@linkplain #getPendingCount pending * count} starts at zero, but may be (atomically) changed using * methods {@link #setPendingCount}, {@link #addToPendingCount}, and * {@link #compareAndSetPendingCount}. Upon invocation of {@link * #tryComplete}, if the pending action count is nonzero, it is * decremented; otherwise, the completion action is performed, and if * this completer itself has a completer, the process is continued * with its completer. As is the case with related synchronization * components such as {@link java.util.concurrent.Phaser Phaser} and * {@link java.util.concurrent.Semaphore Semaphore}, these methods * affect only internal counts; they do not establish any further * internal bookkeeping. In particular, the identities of pending * tasks are not maintained. As illustrated below, you can create * subclasses that do record some or all pending tasks or their * results when needed. As illustrated below, utility methods * supporting customization of completion traversals are also * provided. However, because CountedCompleters provide only basic * synchronization mechanisms, it may be useful to create further * abstract subclasses that maintain linkages, fields, and additional * support methods appropriate for a set of related usages. * * <p>A concrete CountedCompleter class must define method {@link * #compute}, that should in most cases (as illustrated below), invoke * {@code tryComplete()} once before returning. The class may also * optionally override method {@link #onCompletion(CountedCompleter)} * to perform an action upon normal completion, and method * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to * perform an action upon any exception. * * <p>CountedCompleters most often do not bear results, in which case * they are normally declared as {@code CountedCompleter<Void>}, and * will always return {@code null} as a result value. In other cases, * you should override method {@link #getRawResult} to provide a * result from {@code join(), invoke()}, and related methods. In * general, this method should return the value of a field (or a * function of one or more fields) of the CountedCompleter object that * holds the result upon completion. Method {@link #setRawResult} by * default plays no role in CountedCompleters. It is possible, but * rarely applicable, to override this method to maintain other * objects or fields holding result data. * * <p>A CountedCompleter that does not itself have a completer (i.e., * one for which {@link #getCompleter} returns {@code null}) can be * used as a regular ForkJoinTask with this added functionality. * However, any completer that in turn has another completer serves * only as an internal helper for other computations, so its own task * status (as reported in methods such as {@link ForkJoinTask#isDone}) * is arbitrary; this status changes only upon explicit invocations of * {@link #complete}, {@link ForkJoinTask#cancel}, * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon * exceptional completion of method {@code compute}. Upon any * exceptional completion, the exception may be relayed to a task's * completer (and its completer, and so on), if one exists and it has * not otherwise already completed. Similarly, cancelling an internal * CountedCompleter has only a local effect on that completer, so is * not often useful. * * <p><b>Sample Usages.</b> * * <p><b>Parallel recursive decomposition.</b> CountedCompleters may * be arranged in trees similar to those often used with {@link * RecursiveAction}s, although the constructions involved in setting * them up typically vary. Here, the completer of each task is its * parent in the computation tree. Even though they entail a bit more * bookkeeping, CountedCompleters may be better choices when applying * a possibly time-consuming operation (that cannot be further * subdivided) to each element of an array or collection; especially * when the operation takes a significantly different amount of time * to complete for some elements than others, either because of * intrinsic variation (for example I/O) or auxiliary effects such as * garbage collection. Because CountedCompleters provide their own * continuations, other threads need not block waiting to perform * them. * * <p>For example, here is an initial version of a class that uses * divide-by-two recursive decomposition to divide work into single * pieces (leaf tasks). Even when work is split into individual calls, * tree-based techniques are usually preferable to directly forking * leaf tasks, because they reduce inter-thread communication and * improve load balancing. In the recursive case, the second of each * pair of subtasks to finish triggers completion of its parent * (because no result combination is performed, the default no-op * implementation of method {@code onCompletion} is not overridden). * A static utility method sets up the base task and invokes it * (here, implicitly using the {@link ForkJoinPool#commonPool()}). * * <pre> {@code * class MyOperation<E> { void apply(E e) { ... } } * * class ForEach<E> extends CountedCompleter<Void> { * * public static <E> void forEach(E[] array, MyOperation<E> op) { * new ForEach<E>(null, array, op, 0, array.length).invoke(); * } * * final E[] array; final MyOperation<E> op; final int lo, hi; * ForEach(CountedCompleter<?> p, E[] array, MyOperation<E> op, int lo, int hi) { * super(p); * this.array = array; this.op = op; this.lo = lo; this.hi = hi; * } * * public void compute() { // version 1 * if (hi - lo >= 2) { * int mid = (lo + hi) >>> 1; * setPendingCount(2); // must set pending count before fork * new ForEach(this, array, op, mid, hi).fork(); // right child * new ForEach(this, array, op, lo, mid).fork(); // left child * } * else if (hi > lo) * op.apply(array[lo]); * tryComplete(); * } * }}</pre> * * This design can be improved by noticing that in the recursive case, * the task has nothing to do after forking its right task, so can * directly invoke its left task before returning. (This is an analog * of tail recursion removal.) Also, because the task returns upon * executing its left task (rather than falling through to invoke * {@code tryComplete}) the pending count is set to one: * * <pre> {@code * class ForEach<E> ... * public void compute() { // version 2 * if (hi - lo >= 2) { * int mid = (lo + hi) >>> 1; * setPendingCount(1); // only one pending * new ForEach(this, array, op, mid, hi).fork(); // right child * new ForEach(this, array, op, lo, mid).compute(); // direct invoke * } * else { * if (hi > lo) * op.apply(array[lo]); * tryComplete(); * } * } * }</pre> * * As a further improvement, notice that the left task need not even exist. * Instead of creating a new one, we can iterate using the original task, * and add a pending count for each fork. Additionally, because no task * in this tree implements an {@link #onCompletion(CountedCompleter)} method, * {@code tryComplete()} can be replaced with {@link #propagateCompletion}. * * <pre> {@code * class ForEach<E> ... * public void compute() { // version 3 * int l = lo, h = hi; * while (h - l >= 2) { * int mid = (l + h) >>> 1; * addToPendingCount(1); * new ForEach(this, array, op, mid, h).fork(); // right child * h = mid; * } * if (h > l) * op.apply(array[l]); * propagateCompletion(); * } * }</pre> * * Additional improvements of such classes might entail precomputing * pending counts so that they can be established in constructors, * specializing classes for leaf steps, subdividing by say, four, * instead of two per iteration, and using an adaptive threshold * instead of always subdividing down to single elements. * * <p><b>Searching.</b> A tree of CountedCompleters can search for a * value or property in different parts of a data structure, and * report a result in an {@link * java.util.concurrent.atomic.AtomicReference AtomicReference} as * soon as one is found. The others can poll the result to avoid * unnecessary work. (You could additionally {@linkplain #cancel * cancel} other tasks, but it is usually simpler and more efficient * to just let them notice that the result is set and if so skip * further processing.) Illustrating again with an array using full * partitioning (again, in practice, leaf tasks will almost always * process more than one element): * * <pre> {@code * class Searcher<E> extends CountedCompleter<E> { * final E[] array; final AtomicReference<E> result; final int lo, hi; * Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) { * super(p); * this.array = array; this.result = result; this.lo = lo; this.hi = hi; * } * public E getRawResult() { return result.get(); } * public void compute() { // similar to ForEach version 3 * int l = lo, h = hi; * while (result.get() == null && h >= l) { * if (h - l >= 2) { * int mid = (l + h) >>> 1; * addToPendingCount(1); * new Searcher(this, array, result, mid, h).fork(); * h = mid; * } * else { * E x = array[l]; * if (matches(x) && result.compareAndSet(null, x)) * quietlyCompleteRoot(); // root task is now joinable * break; * } * } * tryComplete(); // normally complete whether or not found * } * boolean matches(E e) { ... } // return true if found * * public static <E> E search(E[] array) { * return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke(); * } * }}</pre> * * In this example, as well as others in which tasks have no other * effects except to compareAndSet a common result, the trailing * unconditional invocation of {@code tryComplete} could be made * conditional ({@code if (result.get() == null) tryComplete();}) * because no further bookkeeping is required to manage completions * once the root task completes. * * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine * results of multiple subtasks usually need to access these results * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following * class (that performs a simplified form of map-reduce where mappings * and reductions are all of type {@code E}), one way to do this in * divide and conquer designs is to have each subtask record its * sibling, so that it can be accessed in method {@code onCompletion}. * This technique applies to reductions in which the order of * combining left and right results does not matter; ordered * reductions require explicit left/right designations. Variants of * other streamlinings seen in the above examples may also apply. * * <pre> {@code * class MyMapper<E> { E apply(E v) { ... } } * class MyReducer<E> { E apply(E x, E y) { ... } } * class MapReducer<E> extends CountedCompleter<E> { * final E[] array; final MyMapper<E> mapper; * final MyReducer<E> reducer; final int lo, hi; * MapReducer<E> sibling; * E result; * MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper, * MyReducer<E> reducer, int lo, int hi) { * super(p); * this.array = array; this.mapper = mapper; * this.reducer = reducer; this.lo = lo; this.hi = hi; * } * public void compute() { * if (hi - lo >= 2) { * int mid = (lo + hi) >>> 1; * MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid); * MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi); * left.sibling = right; * right.sibling = left; * setPendingCount(1); // only right is pending * right.fork(); * left.compute(); // directly execute left * } * else { * if (hi > lo) * result = mapper.apply(array[lo]); * tryComplete(); * } * } * public void onCompletion(CountedCompleter<?> caller) { * if (caller != this) { * MapReducer<E> child = (MapReducer<E>)caller; * MapReducer<E> sib = child.sibling; * if (sib == null || sib.result == null) * result = child.result; * else * result = reducer.apply(child.result, sib.result); * } * } * public E getRawResult() { return result; } * * public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) { * return new MapReducer<E>(null, array, mapper, reducer, * 0, array.length).invoke(); * } * }}</pre> * * Here, method {@code onCompletion} takes a form common to many * completion designs that combine results. This callback-style method * is triggered once per task, in either of the two different contexts * in which the pending count is, or becomes, zero: (1) by a task * itself, if its pending count is zero upon invocation of {@code * tryComplete}, or (2) by any of its subtasks when they complete and * decrement the pending count to zero. The {@code caller} argument * distinguishes cases. Most often, when the caller is {@code this}, * no action is necessary. Otherwise the caller argument can be used * (usually via a cast) to supply a value (and/or links to other * values) to be combined. Assuming proper use of pending counts, the * actions inside {@code onCompletion} occur (once) upon completion of * a task and its subtasks. No additional synchronization is required * within this method to ensure thread safety of accesses to fields of * this task or other completed tasks. * * <p><b>Completion Traversals</b>. If using {@code onCompletion} to * process completions is inapplicable or inconvenient, you can use * methods {@link #firstComplete} and {@link #nextComplete} to create * custom traversals. For example, to define a MapReducer that only * splits out right-hand tasks in the form of the third ForEach * example, the completions must cooperatively reduce along * unexhausted subtask links, which can be done as follows: * * <pre> {@code * class MapReducer<E> extends CountedCompleter<E> { // version 2 * final E[] array; final MyMapper<E> mapper; * final MyReducer<E> reducer; final int lo, hi; * MapReducer<E> forks, next; // record subtask forks in list * E result; * MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper, * MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) { * super(p); * this.array = array; this.mapper = mapper; * this.reducer = reducer; this.lo = lo; this.hi = hi; * this.next = next; * } * public void compute() { * int l = lo, h = hi; * while (h - l >= 2) { * int mid = (l + h) >>> 1; * addToPendingCount(1); * (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork(); * h = mid; * } * if (h > l) * result = mapper.apply(array[l]); * // process completions by reducing along and advancing subtask links * for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) { * for (MapReducer t = (MapReducer)c, s = t.forks; s != null; s = t.forks = s.next) * t.result = reducer.apply(t.result, s.result); * } * } * public E getRawResult() { return result; } * * public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) { * return new MapReducer<E>(null, array, mapper, reducer, * 0, array.length, null).invoke(); * } * }}</pre> * * <p><b>Triggers.</b> Some CountedCompleters are themselves never * forked, but instead serve as bits of plumbing in other designs; * including those in which the completion of one or more async tasks * triggers another async task. For example: * * <pre> {@code * class HeaderBuilder extends CountedCompleter<...> { ... } * class BodyBuilder extends CountedCompleter<...> { ... } * class PacketSender extends CountedCompleter<...> { * PacketSender(...) { super(null, 1); ... } // trigger on second completion * public void compute() { } // never called * public void onCompletion(CountedCompleter<?> caller) { sendPacket(); } * } * // sample use: * PacketSender p = new PacketSender(); * new HeaderBuilder(p, ...).fork(); * new BodyBuilder(p, ...).fork(); * }</pre> * * @since 1.8 * @author Doug Lea */ public abstract class CountedCompleter<T> extends ForkJoinTask<T> { private static final long serialVersionUID = 5232453752276485070L; /** This task's completer, or null if none */ final CountedCompleter<?> completer; /** The number of pending tasks until completion */ volatile int pending; /** * Creates a new CountedCompleter with the given completer * and initial pending count. * * @param completer this task's completer, or {@code null} if none * @param initialPendingCount the initial pending count */ protected CountedCompleter(CountedCompleter<?> completer, int initialPendingCount) { this.completer = completer; this.pending = initialPendingCount; } /** * Creates a new CountedCompleter with the given completer * and an initial pending count of zero. * * @param completer this task's completer, or {@code null} if none */ protected CountedCompleter(CountedCompleter<?> completer) { this.completer = completer; } /** * Creates a new CountedCompleter with no completer * and an initial pending count of zero. */ protected CountedCompleter() { this.completer = null; } /** * The main computation performed by this task. */ public abstract void compute(); /** * Performs an action when method {@link #tryComplete} is invoked * and the pending count is zero, or when the unconditional * method {@link #complete} is invoked. By default, this method * does nothing. You can distinguish cases by checking the * identity of the given caller argument. If not equal to {@code * this}, then it is typically a subtask that may contain results * (and/or links to other results) to combine. * * @param caller the task invoking this method (which may * be this task itself) */ public void onCompletion(CountedCompleter<?> caller) { } /** * Performs an action when method {@link * #completeExceptionally(Throwable)} is invoked or method {@link * #compute} throws an exception, and this task has not already * otherwise completed normally. On entry to this method, this task * {@link ForkJoinTask#isCompletedAbnormally}. The return value * of this method controls further propagation: If {@code true} * and this task has a completer that has not completed, then that * completer is also completed exceptionally, with the same * exception as this completer. The default implementation of * this method does nothing except return {@code true}. * * @param ex the exception * @param caller the task invoking this method (which may * be this task itself) * @return {@code true} if this exception should be propagated to this * task's completer, if one exists */ public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) { return true; } /** * Returns the completer established in this task's constructor, * or {@code null} if none. * * @return the completer */ public final CountedCompleter<?> getCompleter() { return completer; } /** * Returns the current pending count. * * @return the current pending count */ public final int getPendingCount() { return pending; } /** * Sets the pending count to the given value. * * @param count the count */ public final void setPendingCount(int count) { pending = count; } /** * Adds (atomically) the given value to the pending count. * * @param delta the value to add */ public final void addToPendingCount(int delta) { int c; do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta)); } /** * Sets (atomically) the pending count to the given count only if * it currently holds the given expected value. * * @param expected the expected value * @param count the new value * @return {@code true} if successful */ public final boolean compareAndSetPendingCount(int expected, int count) { return U.compareAndSwapInt(this, PENDING, expected, count); } /** * If the pending count is nonzero, (atomically) decrements it. * * @return the initial (undecremented) pending count holding on entry * to this method */ public final int decrementPendingCountUnlessZero() { int c; do {} while ((c = pending) != 0 && !U.compareAndSwapInt(this, PENDING, c, c - 1)); return c; } /** * Returns the root of the current computation; i.e., this * task if it has no completer, else its completer's root. * * @return the root of the current computation */ public final CountedCompleter<?> getRoot() { CountedCompleter<?> a = this, p; while ((p = a.completer) != null) a = p; return a; } /** * If the pending count is nonzero, decrements the count; * otherwise invokes {@link #onCompletion(CountedCompleter)} * and then similarly tries to complete this task's completer, * if one exists, else marks this task as complete. */ public final void tryComplete() { CountedCompleter<?> a = this, s = a; for (int c;;) { if ((c = a.pending) == 0) { a.onCompletion(s); if ((a = (s = a).completer) == null) { s.quietlyComplete(); return; } } else if (U.compareAndSwapInt(a, PENDING, c, c - 1)) return; } } /** * Equivalent to {@link #tryComplete} but does not invoke {@link * #onCompletion(CountedCompleter)} along the completion path: * If the pending count is nonzero, decrements the count; * otherwise, similarly tries to complete this task's completer, if * one exists, else marks this task as complete. This method may be * useful in cases where {@code onCompletion} should not, or need * not, be invoked for each completer in a computation. */ public final void propagateCompletion() { CountedCompleter<?> a = this, s = a; for (int c;;) { if ((c = a.pending) == 0) { if ((a = (s = a).completer) == null) { s.quietlyComplete(); return; } } else if (U.compareAndSwapInt(a, PENDING, c, c - 1)) return; } } /** * Regardless of pending count, invokes * {@link #onCompletion(CountedCompleter)}, marks this task as * complete and further triggers {@link #tryComplete} on this * task's completer, if one exists. The given rawResult is * used as an argument to {@link #setRawResult} before invoking * {@link #onCompletion(CountedCompleter)} or marking this task * as complete; its value is meaningful only for classes * overriding {@code setRawResult}. This method does not modify * the pending count. * * <p>This method may be useful when forcing completion as soon as * any one (versus all) of several subtask results are obtained. * However, in the common (and recommended) case in which {@code * setRawResult} is not overridden, this effect can be obtained * more simply using {@code quietlyCompleteRoot();}. * * @param rawResult the raw result */ public void complete(T rawResult) { CountedCompleter<?> p; setRawResult(rawResult); onCompletion(this); quietlyComplete(); if ((p = completer) != null) p.tryComplete(); } /** * If this task's pending count is zero, returns this task; * otherwise decrements its pending count and returns {@code * null}. This method is designed to be used with {@link * #nextComplete} in completion traversal loops. * * @return this task, if pending count was zero, else {@code null} */ public final CountedCompleter<?> firstComplete() { for (int c;;) { if ((c = pending) == 0) return this; else if (U.compareAndSwapInt(this, PENDING, c, c - 1)) return null; } } /** * If this task does not have a completer, invokes {@link * ForkJoinTask#quietlyComplete} and returns {@code null}. Or, if * the completer's pending count is non-zero, decrements that * pending count and returns {@code null}. Otherwise, returns the * completer. This method can be used as part of a completion * traversal loop for homogeneous task hierarchies: * * <pre> {@code * for (CountedCompleter<?> c = firstComplete(); * c != null; * c = c.nextComplete()) { * // ... process c ... * }}</pre> * * @return the completer, or {@code null} if none */ public final CountedCompleter<?> nextComplete() { CountedCompleter<?> p; if ((p = completer) != null) return p.firstComplete(); else { quietlyComplete(); return null; } } /** * Equivalent to {@code getRoot().quietlyComplete()}. */ public final void quietlyCompleteRoot() { for (CountedCompleter<?> a = this, p;;) { if ((p = a.completer) == null) { a.quietlyComplete(); return; } a = p; } } /** * Supports ForkJoinTask exception propagation. */ void internalPropagateException(Throwable ex) { CountedCompleter<?> a = this, s = a; while (a.onExceptionalCompletion(ex, s) && (a = (s = a).completer) != null && a.status >= 0 && a.recordExceptionalCompletion(ex) == EXCEPTIONAL) ; } /** * Implements execution conventions for CountedCompleters. */ protected final boolean exec() { compute(); return false; } /** * Returns the result of the computation. By default, * returns {@code null}, which is appropriate for {@code Void} * actions, but in other cases should be overridden, almost * always to return a field or function of a field that * holds the result upon completion. * * @return the result of the computation */ public T getRawResult() { return null; } /** * A method that result-bearing CountedCompleters may optionally * use to help maintain result data. By default, does nothing. * Overrides are not recommended. However, if this method is * overridden to update existing objects or fields, then it must * in general be defined to be thread-safe. */ protected void setRawResult(T t) { } // Unsafe mechanics private static final sun.misc.Unsafe U; private static final long PENDING; static { try { U = getUnsafe(); PENDING = U.objectFieldOffset (CountedCompleter.class.getDeclaredField("pending")); } catch (Exception e) { throw new Error(e); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. * Replace with a simple call to Unsafe.getUnsafe when integrating * into a jdk. * * @return a sun.misc.Unsafe */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) {} try { return java.security.AccessController.doPrivileged (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } }
{ "task_name": "lcc" }
import sys import os import re import socket import json import time import zipfile import shutil from fnmatch import fnmatch import datetime import tempfile import locale try: # Python 3 from urllib.parse import urlencode, urlparse import compileall str_cls = str except (ImportError): # Python 2 from urllib import urlencode from urlparse import urlparse str_cls = unicode import sublime from .show_error import show_error from .console_write import console_write from .open_compat import open_compat, read_compat from .unicode import unicode_from_os from .clear_directory import clear_directory from .cache import (clear_cache, set_cache, get_cache, merge_cache_under_settings, merge_cache_over_settings, set_cache_under_settings, set_cache_over_settings) from .versions import version_comparable, version_sort from .downloaders.background_downloader import BackgroundDownloader from .downloaders.downloader_exception import DownloaderException from .providers.provider_exception import ProviderException from .clients.client_exception import ClientException from .download_manager import downloader from .providers.channel_provider import ChannelProvider from .upgraders.git_upgrader import GitUpgrader from .upgraders.hg_upgrader import HgUpgrader from .package_io import read_package_file from .providers import CHANNEL_PROVIDERS, REPOSITORY_PROVIDERS from . import __version__ class PackageManager(): """ Allows downloading, creating, installing, upgrading, and deleting packages Delegates metadata retrieval to the CHANNEL_PROVIDERS classes. Uses VcsUpgrader-based classes for handling git and hg repositories in the Packages folder. Downloader classes are utilized to fetch contents of URLs. Also handles displaying package messaging, and sending usage information to the usage server. """ def __init__(self): # Here we manually copy the settings since sublime doesn't like # code accessing settings from threads self.settings = {} settings = sublime.load_settings('Package Control.sublime-settings') for setting in ['timeout', 'repositories', 'channels', 'package_name_map', 'dirs_to_ignore', 'files_to_ignore', 'package_destination', 'cache_length', 'auto_upgrade', 'files_to_ignore_binary', 'files_to_keep', 'dirs_to_keep', 'git_binary', 'git_update_command', 'hg_binary', 'hg_update_command', 'http_proxy', 'https_proxy', 'auto_upgrade_ignore', 'auto_upgrade_frequency', 'submit_usage', 'submit_url', 'renamed_packages', 'files_to_include', 'files_to_include_binary', 'certs', 'ignore_vcs_packages', 'proxy_username', 'proxy_password', 'debug', 'user_agent', 'http_cache', 'http_cache_length', 'install_prereleases', 'openssl_binary']: if settings.get(setting) == None: continue self.settings[setting] = settings.get(setting) # https_proxy will inherit from http_proxy unless it is set to a # string value or false no_https_proxy = self.settings.get('https_proxy') in ["", None] if no_https_proxy and self.settings.get('http_proxy'): self.settings['https_proxy'] = self.settings.get('http_proxy') if self.settings.get('https_proxy') == False: self.settings['https_proxy'] = '' self.settings['platform'] = sublime.platform() self.settings['version'] = sublime.version() # Use the cache to see if settings have changed since the last # time the package manager was created, and clearing any cached # values if they have. previous_settings = get_cache('filtered_settings', {}) # Reduce the settings down to exclude channel info since that will # make the settings always different filtered_settings = self.settings.copy() for key in ['repositories', 'channels', 'package_name_map', 'cache']: if key in filtered_settings: del filtered_settings[key] if filtered_settings != previous_settings and previous_settings != {}: console_write(u'Settings change detected, clearing cache', True) clear_cache() set_cache('filtered_settings', filtered_settings) def get_metadata(self, package): """ Returns the package metadata for an installed package :return: A dict with the keys: version url description or an empty dict on error """ try: debug = self.settings.get('debug') metadata_json = read_package_file(package, 'package-metadata.json', debug=debug) if metadata_json: return json.loads(metadata_json) except (IOError, ValueError) as e: pass return {} def list_repositories(self): """ Returns a master list of all repositories pulled from all sources These repositories come from the channels specified in the "channels" setting, plus any repositories listed in the "repositories" setting. :return: A list of all available repositories """ cache_ttl = self.settings.get('cache_length') repositories = self.settings.get('repositories') channels = self.settings.get('channels') for channel in channels: channel = channel.strip() # Caches various info from channels for performance cache_key = channel + '.repositories' channel_repositories = get_cache(cache_key) merge_cache_under_settings(self, 'package_name_map', channel) merge_cache_under_settings(self, 'renamed_packages', channel) merge_cache_under_settings(self, 'unavailable_packages', channel, list_=True) # If any of the info was not retrieved from the cache, we need to # grab the channel to get it if channel_repositories == None or \ self.settings.get('package_name_map') == None or \ self.settings.get('renamed_packages') == None: for provider_class in CHANNEL_PROVIDERS: if provider_class.match_url(channel): provider = provider_class(channel, self.settings) break try: channel_repositories = provider.get_repositories() set_cache(cache_key, channel_repositories, cache_ttl) for repo in channel_repositories: repo_packages = provider.get_packages(repo) packages_cache_key = repo + '.packages' set_cache(packages_cache_key, repo_packages, cache_ttl) # Have the local name map override the one from the channel name_map = provider.get_name_map() set_cache_under_settings(self, 'package_name_map', channel, name_map, cache_ttl) renamed_packages = provider.get_renamed_packages() set_cache_under_settings(self, 'renamed_packages', channel, renamed_packages, cache_ttl) unavailable_packages = provider.get_unavailable_packages() set_cache_under_settings(self, 'unavailable_packages', channel, unavailable_packages, cache_ttl, list_=True) provider_certs = provider.get_certs() certs = self.settings.get('certs', {}).copy() certs.update(provider_certs) # Save the master list of certs, used by downloaders/cert_provider.py set_cache('*.certs', certs, cache_ttl) except (DownloaderException, ClientException, ProviderException) as e: console_write(e, True) continue repositories.extend(channel_repositories) return [repo.strip() for repo in repositories] def list_available_packages(self): """ Returns a master list of every available package from all sources :return: A dict in the format: { 'Package Name': { # Package details - see example-packages.json for format }, ... } """ if self.settings.get('debug'): console_write(u"Fetching list of available packages", True) console_write(u" Platform: %s-%s" % (sublime.platform(),sublime.arch())) console_write(u" Sublime Text Version: %s" % sublime.version()) console_write(u" Package Control Version: %s" % __version__) cache_ttl = self.settings.get('cache_length') repositories = self.list_repositories() packages = {} bg_downloaders = {} active = [] repos_to_download = [] name_map = self.settings.get('package_name_map', {}) # Repositories are run in reverse order so that the ones first # on the list will overwrite those last on the list for repo in repositories[::-1]: cache_key = repo + '.packages' repository_packages = get_cache(cache_key) if repository_packages != None: packages.update(repository_packages) else: domain = urlparse(repo).hostname if domain not in bg_downloaders: bg_downloaders[domain] = BackgroundDownloader( self.settings, REPOSITORY_PROVIDERS) bg_downloaders[domain].add_url(repo) repos_to_download.append(repo) for bg_downloader in list(bg_downloaders.values()): bg_downloader.start() active.append(bg_downloader) # Wait for all of the downloaders to finish while active: bg_downloader = active.pop() bg_downloader.join() # Grabs the results and stuff it all in the cache for repo in repos_to_download: domain = urlparse(repo).hostname bg_downloader = bg_downloaders[domain] provider = bg_downloader.get_provider(repo) # Allow name mapping of packages for schema version < 2.0 repository_packages = {} for name, info in provider.get_packages(): name = name_map.get(name, name) info['name'] = name repository_packages[name] = info # Display errors we encountered while fetching package info for url, exception in provider.get_failed_sources(): console_write(exception, True) for name, exception in provider.get_broken_packages(): console_write(exception, True) cache_key = repo + '.packages' set_cache(cache_key, repository_packages, cache_ttl) packages.update(repository_packages) renamed_packages = provider.get_renamed_packages() set_cache_under_settings(self, 'renamed_packages', repo, renamed_packages, cache_ttl) unavailable_packages = provider.get_unavailable_packages() set_cache_under_settings(self, 'unavailable_packages', repo, unavailable_packages, cache_ttl, list_=True) return packages def list_packages(self, unpacked_only=False): """ :param unpacked_only: Only list packages that are not inside of .sublime-package files :return: A list of all installed, non-default, package names """ package_names = os.listdir(sublime.packages_path()) package_names = [path for path in package_names if os.path.isdir(os.path.join(sublime.packages_path(), path))] if int(sublime.version()) > 3000 and unpacked_only == False: package_files = os.listdir(sublime.installed_packages_path()) package_names += [f.replace('.sublime-package', '') for f in package_files if re.search('\.sublime-package$', f) != None] # Ignore things to be deleted ignored = ['User'] for package in package_names: cleanup_file = os.path.join(sublime.packages_path(), package, 'package-control.cleanup') if os.path.exists(cleanup_file): ignored.append(package) packages = list(set(package_names) - set(ignored) - set(self.list_default_packages())) packages = sorted(packages, key=lambda s: s.lower()) return packages def list_all_packages(self): """ :return: A list of all installed package names, including default packages""" packages = self.list_default_packages() + self.list_packages() packages = sorted(packages, key=lambda s: s.lower()) return packages def list_default_packages(self): """ :return: A list of all default package names""" if int(sublime.version()) > 3000: bundled_packages_path = os.path.join(os.path.dirname(sublime.executable_path()), 'Packages') files = os.listdir(bundled_packages_path) else: files = os.listdir(os.path.join(os.path.dirname( sublime.packages_path()), 'Pristine Packages')) files = list(set(files) - set(os.listdir( sublime.installed_packages_path()))) packages = [file.replace('.sublime-package', '') for file in files] packages = sorted(packages, key=lambda s: s.lower()) return packages def get_package_dir(self, package): """:return: The full filesystem path to the package directory""" return os.path.join(sublime.packages_path(), package) def get_mapped_name(self, package): """:return: The name of the package after passing through mapping rules""" return self.settings.get('package_name_map', {}).get(package, package) def create_package(self, package_name, package_destination, binary_package=False): """ Creates a .sublime-package file from the running Packages directory :param package_name: The package to create a .sublime-package file for :param package_destination: The full filesystem path of the directory to save the new .sublime-package file in. :param binary_package: If the created package should follow the binary package include/ exclude patterns from the settings. These normally include a setup to exclude .py files and include .pyc files, but that can be changed via settings. :return: bool if the package file was successfully created """ package_dir = self.get_package_dir(package_name) if not os.path.exists(package_dir): show_error(u'The folder for the package name specified, %s, does not exist in %s' % ( package_name, sublime.packages_path())) return False package_filename = package_name + '.sublime-package' package_path = os.path.join(package_destination, package_filename) if not os.path.exists(sublime.installed_packages_path()): os.mkdir(sublime.installed_packages_path()) if os.path.exists(package_path): os.remove(package_path) try: package_file = zipfile.ZipFile(package_path, "w", compression=zipfile.ZIP_DEFLATED) except (OSError, IOError) as e: show_error(u'An error occurred creating the package file %s in %s.\n\n%s' % ( package_filename, package_destination, unicode_from_os(e))) return False if int(sublime.version()) >= 3000: compileall.compile_dir(package_dir, quiet=True, legacy=True, optimize=2) dirs_to_ignore = self.settings.get('dirs_to_ignore', []) if not binary_package: files_to_ignore = self.settings.get('files_to_ignore', []) files_to_include = self.settings.get('files_to_include', []) else: files_to_ignore = self.settings.get('files_to_ignore_binary', []) files_to_include = self.settings.get('files_to_include_binary', []) slash = '\\' if os.name == 'nt' else '/' trailing_package_dir = package_dir + slash if package_dir[-1] != slash else package_dir package_dir_regex = re.compile('^' + re.escape(trailing_package_dir)) for root, dirs, files in os.walk(package_dir): [dirs.remove(dir_) for dir_ in dirs if dir_ in dirs_to_ignore] paths = dirs paths.extend(files) for path in paths: full_path = os.path.join(root, path) relative_path = re.sub(package_dir_regex, '', full_path) ignore_matches = [fnmatch(relative_path, p) for p in files_to_ignore] include_matches = [fnmatch(relative_path, p) for p in files_to_include] if any(ignore_matches) and not any(include_matches): continue if os.path.isdir(full_path): continue package_file.write(full_path, relative_path) package_file.close() return True def install_package(self, package_name): """ Downloads and installs (or upgrades) a package Uses the self.list_available_packages() method to determine where to retrieve the package file from. The install process consists of: 1. Finding the package 2. Downloading the .sublime-package/.zip file 3. Extracting the package file 4. Showing install/upgrade messaging 5. Submitting usage info 6. Recording that the package is installed :param package_name: The package to download and install :return: bool if the package was successfully installed """ packages = self.list_available_packages() is_available = package_name in list(packages.keys()) is_unavailable = package_name in self.settings.get('unavailable_packages', []) if is_unavailable and not is_available: console_write(u'The package "%s" is not available on this platform.' % package_name, True) return False if not is_available: show_error(u'The package specified, %s, is not available' % package_name) return False url = packages[package_name]['download']['url'] package_filename = package_name + '.sublime-package' tmp_dir = tempfile.mkdtemp() try: # This is refers to the zipfile later on, so we define it here so we can # close the zip file if set during the finally clause package_zip = None tmp_package_path = os.path.join(tmp_dir, package_filename) unpacked_package_dir = self.get_package_dir(package_name) package_path = os.path.join(sublime.installed_packages_path(), package_filename) pristine_package_path = os.path.join(os.path.dirname( sublime.packages_path()), 'Pristine Packages', package_filename) if os.path.exists(os.path.join(unpacked_package_dir, '.git')): if self.settings.get('ignore_vcs_packages'): show_error(u'Skipping git package %s since the setting ignore_vcs_packages is set to true' % package_name) return False return GitUpgrader(self.settings['git_binary'], self.settings['git_update_command'], unpacked_package_dir, self.settings['cache_length'], self.settings['debug']).run() elif os.path.exists(os.path.join(unpacked_package_dir, '.hg')): if self.settings.get('ignore_vcs_packages'): show_error(u'Skipping hg package %s since the setting ignore_vcs_packages is set to true' % package_name) return False return HgUpgrader(self.settings['hg_binary'], self.settings['hg_update_command'], unpacked_package_dir, self.settings['cache_length'], self.settings['debug']).run() old_version = self.get_metadata(package_name).get('version') is_upgrade = old_version != None # Download the sublime-package or zip file try: with downloader(url, self.settings) as manager: package_bytes = manager.fetch(url, 'Error downloading package.') except (DownloaderException) as e: console_write(e, True) show_error(u'Unable to download %s. Please view the console for more details.' % package_name) return False with open_compat(tmp_package_path, "wb") as package_file: package_file.write(package_bytes) # Try to open it as a zip file try: package_zip = zipfile.ZipFile(tmp_package_path, 'r') except (zipfile.BadZipfile): show_error(u'An error occurred while trying to unzip the package file for %s. Please try installing the package again.' % package_name) return False # Scan through the root level of the zip file to gather some info root_level_paths = [] last_path = None for path in package_zip.namelist(): try: if not isinstance(path, str_cls): path = path.decode('utf-8', 'strict') except (UnicodeDecodeError): console_write(u'One or more of the zip file entries in %s is not encoded using UTF-8, aborting' % package_name, True) return False last_path = path if path.find('/') in [len(path) - 1, -1]: root_level_paths.append(path) # Make sure there are no paths that look like security vulnerabilities if path[0] == '/' or path.find('../') != -1 or path.find('..\\') != -1: show_error(u'The package specified, %s, contains files outside of the package dir and cannot be safely installed.' % package_name) return False if last_path and len(root_level_paths) == 0: root_level_paths.append(last_path[0:last_path.find('/') + 1]) # If there is only a single directory at the top leve, the file # is most likely a zip from BitBucket or GitHub and we need # to skip the top-level dir when extracting skip_root_dir = len(root_level_paths) == 1 and \ root_level_paths[0].endswith('/') no_package_file_zip_path = '.no-sublime-package' if skip_root_dir: no_package_file_zip_path = root_level_paths[0] + no_package_file_zip_path # If we should extract unpacked or as a .sublime-package file unpack = True # By default, ST3 prefers .sublime-package files since this allows # overriding files in the Packages/{package_name}/ folder if int(sublime.version()) >= 3000: unpack = False # If the package maintainer doesn't want a .sublime-package try: package_zip.getinfo(no_package_file_zip_path) unpack = True except (KeyError): pass # If we already have a package-metadata.json file in # Packages/{package_name}/, the only way to successfully upgrade # will be to unpack unpacked_metadata_file = os.path.join(unpacked_package_dir, 'package-metadata.json') if os.path.exists(unpacked_metadata_file): unpack = True # If we determined it should be unpacked, we extract directly # into the Packages/{package_name}/ folder if unpack: self.backup_package_dir(package_name) package_dir = unpacked_package_dir # Otherwise we go into a temp dir since we will be creating a # new .sublime-package file later else: tmp_working_dir = os.path.join(tmp_dir, 'working') os.mkdir(tmp_working_dir) package_dir = tmp_working_dir package_metadata_file = os.path.join(package_dir, 'package-metadata.json') if not os.path.exists(package_dir): os.mkdir(package_dir) os.chdir(package_dir) # Here we don't use .extractall() since it was having issues on OS X overwrite_failed = False extracted_paths = [] for path in package_zip.namelist(): dest = path try: if not isinstance(dest, str_cls): dest = dest.decode('utf-8', 'strict') except (UnicodeDecodeError): console_write(u'One or more of the zip file entries in %s is not encoded using UTF-8, aborting' % package_name, True) return False if os.name == 'nt': regex = ':|\*|\?|"|<|>|\|' if re.search(regex, dest) != None: console_write(u'Skipping file from package named %s due to an invalid filename' % package_name, True) continue # If there was only a single directory in the package, we remove # that folder name from the paths as we extract entries if skip_root_dir: dest = dest[len(root_level_paths[0]):] if os.name == 'nt': dest = dest.replace('/', '\\') else: dest = dest.replace('\\', '/') dest = os.path.join(package_dir, dest) def add_extracted_dirs(dir_): while dir_ not in extracted_paths: extracted_paths.append(dir_) dir_ = os.path.dirname(dir_) if dir_ == package_dir: break if path.endswith('/'): if not os.path.exists(dest): os.makedirs(dest) add_extracted_dirs(dest) else: dest_dir = os.path.dirname(dest) if not os.path.exists(dest_dir): os.makedirs(dest_dir) add_extracted_dirs(dest_dir) extracted_paths.append(dest) try: open_compat(dest, 'wb').write(package_zip.read(path)) except (IOError) as e: message = unicode_from_os(e) if re.search('[Ee]rrno 13', message): overwrite_failed = True break console_write(u'Skipping file from package named %s due to an invalid filename' % package_name, True) except (UnicodeDecodeError): console_write(u'Skipping file from package named %s due to an invalid filename' % package_name, True) package_zip.close() package_zip = None # If upgrading failed, queue the package to upgrade upon next start if overwrite_failed: reinstall_file = os.path.join(package_dir, 'package-control.reinstall') open_compat(reinstall_file, 'w').close() # Don't delete the metadata file, that way we have it # when the reinstall happens, and the appropriate # usage info can be sent back to the server clear_directory(package_dir, [reinstall_file, package_metadata_file]) show_error(u'An error occurred while trying to upgrade %s. Please restart Sublime Text to finish the upgrade.' % package_name) return False # Here we clean out any files that were not just overwritten. It is ok # if there is an error removing a file. The next time there is an # upgrade, it should be cleaned out successfully then. clear_directory(package_dir, extracted_paths) self.print_messages(package_name, package_dir, is_upgrade, old_version) with open_compat(package_metadata_file, 'w') as f: metadata = { "version": packages[package_name]['download']['version'], "url": packages[package_name]['homepage'], "description": packages[package_name]['description'] } json.dump(metadata, f) # Submit install and upgrade info if is_upgrade: params = { 'package': package_name, 'operation': 'upgrade', 'version': packages[package_name]['download']['version'], 'old_version': old_version } else: params = { 'package': package_name, 'operation': 'install', 'version': packages[package_name]['download']['version'] } self.record_usage(params) # Record the install in the settings file so that you can move # settings across computers and have the same packages installed def save_package(): settings = sublime.load_settings('Package Control.sublime-settings') installed_packages = settings.get('installed_packages', []) if not installed_packages: installed_packages = [] installed_packages.append(package_name) installed_packages = list(set(installed_packages)) installed_packages = sorted(installed_packages, key=lambda s: s.lower()) settings.set('installed_packages', installed_packages) sublime.save_settings('Package Control.sublime-settings') sublime.set_timeout(save_package, 1) # If we didn't extract directly into the Packages/{package_name}/ # folder, we need to create a .sublime-package file and install it if not unpack: try: # Remove the downloaded file since we are going to overwrite it os.remove(tmp_package_path) package_zip = zipfile.ZipFile(tmp_package_path, "w", compression=zipfile.ZIP_DEFLATED) except (OSError, IOError) as e: show_error(u'An error occurred creating the package file %s in %s.\n\n%s' % ( package_filename, tmp_dir, unicode_from_os(e))) return False package_dir_regex = re.compile('^' + re.escape(package_dir)) for root, dirs, files in os.walk(package_dir): paths = dirs paths.extend(files) for path in paths: full_path = os.path.join(root, path) relative_path = re.sub(package_dir_regex, '', full_path) if os.path.isdir(full_path): continue package_zip.write(full_path, relative_path) package_zip.close() package_zip = None if os.path.exists(package_path): os.remove(package_path) shutil.move(tmp_package_path, package_path) # We have to remove the pristine package too or else Sublime Text 2 # will silently delete the package if os.path.exists(pristine_package_path): os.remove(pristine_package_path) os.chdir(sublime.packages_path()) return True finally: # We need to make sure the zipfile is closed to # help prevent permissions errors on Windows if package_zip: package_zip.close() # Try to remove the tmp dir after a second to make sure # a virus scanner is holding a reference to the zipfile # after we close it. def remove_tmp_dir(): try: shutil.rmtree(tmp_dir) except (PermissionError): # If we can't remove the tmp dir, don't let an uncaught exception # fall through and break the install process pass sublime.set_timeout(remove_tmp_dir, 1000) def backup_package_dir(self, package_name): """ Does a full backup of the Packages/{package}/ dir to Backup/ :param package_name: The name of the package to back up :return: If the backup succeeded """ package_dir = os.path.join(sublime.packages_path(), package_name) if not os.path.exists(package_dir): return True try: backup_dir = os.path.join(os.path.dirname( sublime.packages_path()), 'Backup', datetime.datetime.now().strftime('%Y%m%d%H%M%S')) if not os.path.exists(backup_dir): os.makedirs(backup_dir) package_backup_dir = os.path.join(backup_dir, package_name) if os.path.exists(package_backup_dir): console_write(u"FOLDER %s ALREADY EXISTS!" % package_backup_dir) shutil.copytree(package_dir, package_backup_dir) return True except (OSError, IOError) as e: show_error(u'An error occurred while trying to backup the package directory for %s.\n\n%s' % ( package_name, unicode_from_os(e))) if os.path.exists(package_backup_dir): shutil.rmtree(package_backup_dir) return False def print_messages(self, package, package_dir, is_upgrade, old_version): """ Prints out package install and upgrade messages The functionality provided by this allows package maintainers to show messages to the user when a package is installed, or when certain version upgrade occur. :param package: The name of the package the message is for :param package_dir: The full filesystem path to the package directory :param is_upgrade: If the install was actually an upgrade :param old_version: The string version of the package before the upgrade occurred """ messages_file = os.path.join(package_dir, 'messages.json') if not os.path.exists(messages_file): return messages_fp = open_compat(messages_file, 'r') try: message_info = json.loads(read_compat(messages_fp)) except (ValueError): console_write(u'Error parsing messages.json for %s' % package, True) return messages_fp.close() output = '' if not is_upgrade and message_info.get('install'): install_messages = os.path.join(package_dir, message_info.get('install')) message = '\n\n%s:\n%s\n\n ' % (package, ('-' * len(package))) with open_compat(install_messages, 'r') as f: message += read_compat(f).replace('\n', '\n ') output += message + '\n' elif is_upgrade and old_version: upgrade_messages = list(set(message_info.keys()) - set(['install'])) upgrade_messages = version_sort(upgrade_messages, reverse=True) old_version_cmp = version_comparable(old_version) for version in upgrade_messages: if version_comparable(version) <= old_version_cmp: break if not output: message = '\n\n%s:\n%s\n' % (package, ('-' * len(package))) output += message upgrade_message_path = os.path.join(package_dir, message_info.get(version)) message = '\n ' with open_compat(upgrade_message_path, 'r') as f: message += read_compat(f).replace('\n', '\n ') output += message + '\n' if not output: return def print_to_panel(): window = sublime.active_window() views = window.views() view = None for _view in views: if _view.name() == 'Package Control Messages': view = _view break if not view: view = window.new_file() view.set_name('Package Control Messages') view.set_scratch(True) def write(string): view.run_command('package_message', {'string': string}) if not view.size(): view.settings().set("word_wrap", True) write('Package Control Messages\n' + '========================') write(output) sublime.set_timeout(print_to_panel, 1) def remove_package(self, package_name): """ Deletes a package The deletion process consists of: 1. Deleting the directory (or marking it for deletion if deletion fails) 2. Submitting usage info 3. Removing the package from the list of installed packages :param package_name: The package to delete :return: bool if the package was successfully deleted """ installed_packages = self.list_packages() if package_name not in installed_packages: show_error(u'The package specified, %s, is not installed' % package_name) return False os.chdir(sublime.packages_path()) # Give Sublime Text some time to ignore the package time.sleep(1) package_filename = package_name + '.sublime-package' installed_package_path = os.path.join(sublime.installed_packages_path(), package_filename) pristine_package_path = os.path.join(os.path.dirname( sublime.packages_path()), 'Pristine Packages', package_filename) package_dir = self.get_package_dir(package_name) version = self.get_metadata(package_name).get('version') try: if os.path.exists(installed_package_path): os.remove(installed_package_path) except (OSError, IOError) as e: show_error(u'An error occurred while trying to remove the installed package file for %s.\n\n%s' % ( package_name, unicode_from_os(e))) return False try: if os.path.exists(pristine_package_path): os.remove(pristine_package_path) except (OSError, IOError) as e: show_error(u'An error occurred while trying to remove the pristine package file for %s.\n\n%s' % ( package_name, unicode_from_os(e))) return False # We don't delete the actual package dir immediately due to a bug # in sublime_plugin.py can_delete_dir = True if not clear_directory(package_dir): # If there is an error deleting now, we will mark it for # cleanup the next time Sublime Text starts open_compat(os.path.join(package_dir, 'package-control.cleanup'), 'w').close() can_delete_dir = False params = { 'package': package_name, 'operation': 'remove', 'version': version } self.record_usage(params) # Remove the package from the installed packages list def clear_package(): settings = sublime.load_settings('Package Control.sublime-settings') installed_packages = settings.get('installed_packages', []) if not installed_packages: installed_packages = [] installed_packages.remove(package_name) settings.set('installed_packages', installed_packages) sublime.save_settings('Package Control.sublime-settings') sublime.set_timeout(clear_package, 1) if can_delete_dir and os.path.exists(package_dir): os.rmdir(package_dir) return True def record_usage(self, params): """ Submits install, upgrade and delete actions to a usage server The usage information is currently displayed on the Package Control community package list at http://wbond.net/sublime_packages/community :param params: A dict of the information to submit """ if not self.settings.get('submit_usage'): return params['package_control_version'] = \ self.get_metadata('Package Control').get('version') params['sublime_platform'] = self.settings.get('platform') params['sublime_version'] = self.settings.get('version') # For Python 2, we need to explicitly encoding the params for param in params: if isinstance(params[param], str_cls): params[param] = params[param].encode('utf-8') url = self.settings.get('submit_url') + '?' + urlencode(params) try: with downloader(url, self.settings) as manager: result = manager.fetch(url, 'Error submitting usage information.') except (DownloaderException) as e: console_write(e, True) return try: result = json.loads(result.decode('utf-8')) if result['result'] != 'success': raise ValueError() except (ValueError): console_write(u'Error submitting usage information for %s' % params['package'], True)
{ "task_name": "lcc" }
Passage 1: Apothecary to the Household at Windsor Apothecary to the Household at Windsor is an officer of the Medical Household of the Royal Household of the Sovereign of the United Kingdom. He has a salaried daily surgery. The current Apothecary to the Household at Windsor, is Jonathan Holliday. Passage 2: Chamberlain (office) A chamberlain (Medieval Latin: "cambellanus" or "cambrerius", with charge of treasury "camerarius") is a senior royal official in charge of managing a royal household. Historically, the chamberlain superintends the arrangement of domestic affairs and was often also charged with receiving and paying out money kept in the royal chamber. The position was usually honoured upon a high-ranking member of the nobility (nobleman) or the clergy, often a royal favourite. Roman emperors appointed this officer under the title of "cubicularius". The papal chamberlain of the Pope enjoys very extensive powers, having the revenues of the papal household under his charge. As a sign of their dignity, they bore a key, which in the seventeenth century was often silvered, and actually fitted the door-locks of chamber rooms, since the eighteenth century it had turned into a merely symbolic, albeit splendid, rank-insignia of gilded bronze. In many countries there are ceremonial posts associated with the household of the sovereign. Passage 3: Royal Communications Royal Communications is a branch of the Private Secretary's Office of the Royal Household of the Sovereign of the United Kingdom responsible for media relations and communicating with various organisations and authorities on matters to do with The Queen and the Royal Family. Until early 2014, Royal Communications was known as the Royal Household Press Office. Passage 4: Household of Queen Elizabeth II The Royal Households of the United Kingdom consists of royal officials and the supporting staff of the British Royal Family, as well as the Royal Household which supports the Sovereign. Each member of the Royal Family who undertakes public duties has his own separate Household. When Elizabeth II succeeded her father George VI as sovereign of the United Kingdom, she appointed a new household. Passage 5: Earl of Winchilsea Earl of Winchilsea is a title in the Peerage of England held by the Finch-Hatton family. It has been united with the title of Earl of Nottingham under a single holder since 1729. The Finch family is believed to be descended from Henry FitzHerbert, Lord Chamberlain to Henry I (r. 1100–1135). The name change came in the 1350s after marriage to an heiress member of the Finch family. A later member of the family, Sir William Finch, was knighted in 1513. His son Sir Thomas Finch (died 1563), was also knighted for his share in suppressing Sir Thomas Wyatt's insurrection against Queen Mary I, and was the son-in-law of Sir Thomas Moyle, some of whose lands Finch's wife inherited. Thomas's eldest son Moyle Finch represented Weymouth, Kent and Winchelsea in the House of Commons. In 1611 he was created a baronet, of Eastwell in the County of Kent. Passage 6: Lord Chamberlain The Lord Chamberlain or Lord Chamberlain of the Household is the senior officer of the Royal Household of the United Kingdom, supervising the departments which support and provide advice to the Sovereign of the United Kingdom. Passage 7: Vice-Chamberlain of the Household The Vice-Chamberlain of the Household is a member of the Royal Household of the Sovereign of the United Kingdom. The office-holder is usually a junior government whip in the British House of Commons ranking third or fourth after the Chief Whip and the Deputy Chief Whip. He or she is the Deputy to the Lord Chamberlain of the Household. The Vice-Chamberlain's main roles are to compile a daily private report to the Sovereign on proceedings in the House of Commons and to relay addresses from the Commons to the Sovereign and back. As a member of the Royal Household, the Vice-Chamberlain accompanies the Sovereign and Royal Household at certain diplomatic and social events, particularly the annual garden party at Buckingham Palace. When the Sovereign goes in procession to Westminster for the State Opening of Parliament, the Vice-Chamberlain stays and is "held captive" at Buckingham Palace. This custom began with the Restoration (1660), because of the previous Vice-Chamberlain's role in the beheading of Charles I. Passage 8: Lord Michael Fitzalan-Howard Major General Lord Michael Fitzalan-Howard, (22 October 1916 – 2 November 2007) was a senior officer in the British Army. He later served as Marshal of the Diplomatic Corps in the British Royal Household for nine years until 1981, and Gold Stick-in-Waiting and Colonel of the Life Guards for 20 years, finally retiring in 1999. Passage 9: Serjeant Surgeon The Serjeant Surgeon is the senior surgeon in the Medical Household of the Royal Household of the Sovereign of the United Kingdom. The origin of the post dates back to 1253. Early Serjeant Surgeons were military surgeons who followed their King into battle. John of Arderne, later famous as the Father of Proctology, accompanied Edward III at the Battle of Crecy in 1346. But the title did not refer to a military rank; the word "Serjeant" comes from the Latin "serviens" or "serving". Over the years, other duties of the Serjeant Surgeon have included embalming of the royal corpse, oversight of torture to ensure the prisoner was not killed, and the screening of applicants to be touched by the King for the cure of the King's Evil (tuberculous glands of the neck)! The first knighthood to be granted to a Serjeant Surgeon was in the reign of Henry VIII, to John Aylef, who was said to have cured the King of a fistula. The first Serjeant Surgeon to receive a peerage was Joseph Lister, the founder of antiseptic surgery, who was created Baron Lister of Lyme Regis in the County of Dorset by Queen Victoria. Passage 10: British Royal Train In the United Kingdom, the Royal Train is used to convey senior members of the British Royal Family and associated staff of the Royal Household around the railway network of Great Britain. It is formed from a dedicated set of claret liveried sleeper, dining and lounge carriages. The current stock dates from 1977-1987. They are arranged according to requirements, and stored when not in use. The earliest royal coaches date back to the mid-19th Century in the reign of Queen Victoria; until an upgrade in 1977 there were multiple sets based in different regions, a legacy of the pre-nationalisation era of railways in Britain. Many are now in museums or on heritage railways; the National Railway Museum in York has a royal themed exhibition. Dedicated locomotives have never traditionally been part of the Royal Train, first appearing in special livery only in the 1990s, but also seeing use on other trains since 2003. In the 21st Century, various preserved (and one new build) steam locomotives have also hauled the train on special occasions. Although regularly cited by critics as one of the unnecessary luxuries of the Royal Family, which has led to an increase in the alternate use of normal scheduled services where possible, supporters argue the current arrangement emphasizes utility over luxury, and is still often the most practical and secure mode of travel to fit the required itinerary and avoid disruption to the public. Question: What is the name of the Finch Family's famous relative who was the senior officer of the Royal Household in the United Kingdom? Answer: Lord Chamberlain
{ "task_name": "hotpotqa" }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Amazon; using Amazon.Runtime; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; using ASC.Common.Logging; using ASC.Common.Utils; using ASC.Notify.Messages; using ASC.Notify.Patterns; namespace ASC.Core.Notify.Senders { class AWSSender : SmtpSender { private static readonly ILog log = LogManager.GetLogger("ASC.Notify.AmazonSES"); private readonly object locker = new object(); private AmazonSimpleEmailServiceClient ses; private TimeSpan refreshTimeout; private DateTime lastRefresh; private DateTime lastSend; private TimeSpan sendWindow = TimeSpan.MinValue; private GetSendQuotaResponse quota; public override void Init(IDictionary<string, string> properties) { base.Init(properties); var region = properties.ContainsKey("region") ? RegionEndpoint.GetBySystemName(properties["region"]) : RegionEndpoint.USEast1; ses = new AmazonSimpleEmailServiceClient(properties["accessKey"], properties["secretKey"], region); refreshTimeout = TimeSpan.Parse(properties.ContainsKey("refreshTimeout") ? properties["refreshTimeout"] : "0:30:0"); lastRefresh = DateTime.UtcNow - refreshTimeout; //set to refresh on first send } public override NoticeSendResult Send(NotifyMessage m) { var result = default(NoticeSendResult); try { try { Log.DebugFormat("Tenant: {0}, To: {1}", m.Tenant, m.To); CoreContext.TenantManager.SetCurrentTenant(m.Tenant); if (!CoreContext.Configuration.SmtpSettings.IsDefaultSettings) { _useCoreSettings = true; result = base.Send(m); _useCoreSettings = false; } else { result = SendMessage(m); } Log.DebugFormat(result.ToString()); } catch (Exception e) { Log.ErrorFormat("Tenant: {0}, To: {1} - {2}", m.Tenant, m.To, e); throw; } } catch (ArgumentException) { result = NoticeSendResult.MessageIncorrect; } catch (MessageRejectedException) { result = NoticeSendResult.SendingImpossible; } catch (AmazonSimpleEmailServiceException e) { result = e.ErrorType == ErrorType.Sender ? NoticeSendResult.MessageIncorrect : NoticeSendResult.TryOnceAgain; } catch (Exception) { result = NoticeSendResult.SendingImpossible; } if (result == NoticeSendResult.MessageIncorrect || result == NoticeSendResult.SendingImpossible) { log.DebugFormat("Amazon sending failed: {0}, fallback to smtp", result); result = base.Send(m); } return result; } private NoticeSendResult SendMessage(NotifyMessage m) { //Check if we need to query stats RefreshQuotaIfNeeded(); if (quota != null) { lock (locker) { if (quota.Max24HourSend <= quota.SentLast24Hours) { //Quota exceeded, queue next refresh to +24 hours lastRefresh = DateTime.UtcNow.AddHours(24); log.WarnFormat("Quota limit reached. setting next check to: {0}", lastRefresh); return NoticeSendResult.SendingImpossible; } } } var dest = new Destination { ToAddresses = m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => MailAddressUtils.Create(a).Address).ToList(), }; var subject = new Content(MimeHeaderUtils.EncodeMime(m.Subject)) { Charset = Encoding.UTF8.WebName, }; Body body; if (m.ContentType == Pattern.HTMLContentType) { body = new Body(new Content(HtmlUtil.GetText(m.Content)) { Charset = Encoding.UTF8.WebName }); body.Html = new Content(GetHtmlView(m.Content)) { Charset = Encoding.UTF8.WebName }; } else { body = new Body(new Content(m.Content) { Charset = Encoding.UTF8.WebName }); } var from = MailAddressUtils.Create(m.From).ToEncodedString(); var request = new SendEmailRequest { Source = from, Destination = dest, Message = new Message(subject, body) }; if (!string.IsNullOrEmpty(m.ReplyTo)) { request.ReplyToAddresses.Add(MailAddressUtils.Create(m.ReplyTo).Address); } ThrottleIfNeeded(); var response = ses.SendEmail(request); lastSend = DateTime.UtcNow; return response != null ? NoticeSendResult.OK : NoticeSendResult.TryOnceAgain; } private void ThrottleIfNeeded() { //Check last send and throttle if needed if (sendWindow != TimeSpan.MinValue) { if (DateTime.UtcNow - lastSend <= sendWindow) { //Possible BUG: at high frequncies maybe bug with to little differences //This means that time passed from last send is less then message per second log.DebugFormat("Send rate doesn't fit in send window. sleeping for: {0}", sendWindow); Thread.Sleep(sendWindow); } } } private void RefreshQuotaIfNeeded() { if (!IsRefreshNeeded()) return; lock (locker) { if (IsRefreshNeeded())//Double check { log.DebugFormat("refreshing qouta. interval: {0} Last refresh was at: {1}", refreshTimeout, lastRefresh); //Do quota refresh lastRefresh = DateTime.UtcNow.AddMinutes(1); try { var r = new GetSendQuotaRequest(); quota = ses.GetSendQuota(r); sendWindow = TimeSpan.FromSeconds(1.0 / quota.MaxSendRate); log.DebugFormat("quota: {0}/{1} at {2} mps. send window:{3}", quota.SentLast24Hours, quota.Max24HourSend, quota.MaxSendRate, sendWindow); } catch (Exception e) { log.Error("error refreshing quota", e); } } } } private bool IsRefreshNeeded() { return quota == null || (DateTime.UtcNow - lastRefresh) > refreshTimeout; } } }
{ "task_name": "lcc" }
Passage 1: Benjamin Stoloff Benjamin Stoloff( October 6, 1895 – September 8, 1960) was an American film director and producer. He began his career as a short film comedy director and gradually moved into feature film directing and production later in his career. Passage 2: Stephen Goosson Stephen Goosson( March 24, 1889- March 25, 1973) was an American film set designer and art director. Born in Grand Rapids, Michigan, Goosson was an architect in Detroit before starting his film career as art director for producer Lewis J. Selznick, and films for Fox Film Corporation such as" New Movietone Follies of 1930". He eventually was hired by Columbia Pictures, where he served as supervising art director for 25 years. Goosson won the Academy Award for Best Art Direction for" Lost Horizon". His designs for the film have been noted as excellent examples of the Streamline Moderne style that reached the height of its popularity that year. Additional credits include" Mr. Deeds Goes to TownTheodora Goes Wild The Awful TruthHoliday Meet John Doe The Little Foxes The Jolson Story", and" The Lady from Shanghai". Goosson died of a stroke in Woodland Hills, California. Passage 3: Elizabeth Cuthrell Elizabeth Cuthrell is a writer, producer and co-founder of Evenstar Films, a New York City- based Production company. Passage 4: New Movietone Follies of 1930 New Movietone Follies of 1930 is a 1930 American Pre- Code musical film released by Fox Film Corporation, directed by Benjamin Stoloff. The film stars El Brendel and Marjorie White who also costarred in Fox's" Just Imagine" in 1930. The film is a follow- up to" Fox Movietone Follies of 1929" and has sequences filmed in Multicolor. An archival 35 mm print of the film is in the collection of the UCLA Film and Television Archive. Passage 5: Unfinished Business (1985 Australian film) Unfinished Business is a 1985 Australian film directed by Bob Ellis and starring John Clayton, Michele Fawdon, Norman Kaye, and Call Ricketson. " Unfinished Business" was nominated for 5 AFI Awards. Passage 6: Unfinished Business (1941 film) Unfinished Business is a 1941 American romantic comedy film produced and directed by Gregory La Cava and starring Irene Dunne, Robert Montgomery and Preston Foster. The screenplay concerns a young woman who quickly falls in love with a playboy, but when he shows no interest in making her his wife, marries his brother. Passage 7: Michael Tow Michael Tow is an Asian- American actor, director and producer. He is best known for his work on" Lucky GrandmaBlindspot" and" Unfinished Business". Passage 8: Fox Movietone Follies of 1929 Fox Movietone Follies of 1929, also known as Movietone Follies of 1929 and The William Fox Movietone Follies of 1929, is a black- and- white and color American musical film released by Fox Film Corporation. Passage 9: Mr. Right (2009 film) Mr. Right is a 2009 British film directed by David Morris and Jacqui Morris. The jointly- made gay- themed film is the debut for both directors. Passage 10: Gregory La Cava Gregory La Cava( March 10, 1892 – March 1, 1952) was an American film director of Italian descent best known for his films of the 1930s, including" My Man Godfrey" and" Stage Door", which earned him nominations for Academy Award for Best Director. Question: Do both directors of films New Movietone Follies Of 1930 and Unfinished Business (1941 Film) share the same nationality? Answer: yes
{ "task_name": "2WikiMultihopQA" }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you 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. */ package io.druid.segment.loading; import com.google.common.io.ByteStreams; import io.druid.java.util.common.StringUtils; import io.druid.storage.hdfs.HdfsFileTimestampVersionFinder; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.file.Files; import java.util.regex.Pattern; public class HdfsFileTimestampVersionFinderTest { private static MiniDFSCluster miniCluster; private static File hdfsTmpDir; private static URI uriBase; private static Path filePath = new Path("/tmp/foo"); private static Path perTestPath = new Path("/tmp/tmp2"); private static String pathContents = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; private static byte[] pathByteContents = StringUtils.toUtf8(pathContents); private static Configuration conf; @BeforeClass public static void setupStatic() throws IOException, ClassNotFoundException { hdfsTmpDir = File.createTempFile("hdfsHandlerTest", "dir"); if (!hdfsTmpDir.delete()) { throw new IOException(String.format("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath())); } conf = new Configuration(true); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath()); miniCluster = new MiniDFSCluster.Builder(conf).build(); uriBase = miniCluster.getURI(0); final File tmpFile = File.createTempFile("hdfsHandlerTest", ".data"); tmpFile.delete(); try { Files.copy(new ByteArrayInputStream(pathByteContents), tmpFile.toPath()); try (OutputStream stream = miniCluster.getFileSystem().create(filePath)) { Files.copy(tmpFile.toPath(), stream); } } finally { tmpFile.delete(); } } @AfterClass public static void tearDownStatic() throws IOException { if (miniCluster != null) { miniCluster.shutdown(true); } FileUtils.deleteDirectory(hdfsTmpDir); } private HdfsFileTimestampVersionFinder finder; @Before public void setUp() { finder = new HdfsFileTimestampVersionFinder(conf); } @After public void tearDown() throws IOException { miniCluster.getFileSystem().delete(perTestPath, true); } @Test public void testSimpleLatestVersion() throws IOException, InterruptedException { final Path oldPath = new Path(perTestPath, "555test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(oldPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(oldPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Thread.sleep(10); final Path newPath = new Path(perTestPath, "666test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(newPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(newPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Assert.assertEquals(newPath.toString(), finder.getLatestVersion(oldPath.toUri(), Pattern.compile(".*")).getPath()); } @Test public void testAlreadyLatestVersion() throws IOException, InterruptedException { final Path oldPath = new Path(perTestPath, "555test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(oldPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(oldPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Thread.sleep(10); final Path newPath = new Path(perTestPath, "666test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(newPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(newPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Assert.assertEquals(newPath.toString(), finder.getLatestVersion(newPath.toUri(), Pattern.compile(".*")).getPath()); } @Test public void testNoLatestVersion() throws IOException, InterruptedException { final Path oldPath = new Path(perTestPath, "555test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(oldPath)); Assert.assertNull(finder.getLatestVersion(oldPath.toUri(), Pattern.compile(".*"))); } @Test public void testSimpleLatestVersionInDir() throws IOException, InterruptedException { final Path oldPath = new Path(perTestPath, "555test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(oldPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(oldPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Thread.sleep(10); final Path newPath = new Path(perTestPath, "666test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(newPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(newPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Assert.assertEquals( newPath.toString(), finder.getLatestVersion(perTestPath.toUri(), Pattern.compile(".*test\\.txt")).getPath() ); } @Test public void testSkipMismatch() throws IOException, InterruptedException { final Path oldPath = new Path(perTestPath, "555test.txt"); Assert.assertFalse(miniCluster.getFileSystem().exists(oldPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(oldPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Thread.sleep(10); final Path newPath = new Path(perTestPath, "666test.txt2"); Assert.assertFalse(miniCluster.getFileSystem().exists(newPath)); try (final OutputStream outputStream = miniCluster.getFileSystem().create(newPath); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, outputStream); } Assert.assertEquals( oldPath.toString(), finder.getLatestVersion(perTestPath.toUri(), Pattern.compile(".*test\\.txt")).getPath() ); } }
{ "task_name": "lcc" }
Passage 1: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 2: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 3: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 4: The Irony of Fate 2 The Irony of Fate 2 or The Irony of Fate: Continuation(" Ironiya sud ’by. Prodolzheniye") is a 2007 Russian romantic comedy film directed by Timur Bekmambetov based on a screenplay by Aleksey Slapovsky produced by Channel One and released by Mosfilm. It is a direct sequel of the first" The Irony of Fate". It was originally rumored to be put in production in a press release, dedicated to the original movie's 30th anniversary in 2005. " Irony of Fate" earned$ 55,000,000 in total from its gross box- office release, with$ 49,000,000 coming from the Russian box- office alone. Passage 5: Ivar Campbell Ivar Campbell (born 1904, died 1985), full name Donald Robert Ivar Campbell, was a New Zealand screenwriter and film director. Son of Lt-Col Robert Ormus Campbell and Beatrice (née Cadell). Passage 6: Eyes of Texas (film) Eyes of Texas is a 1948 American film directed by William Witney. Passage 7: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 8: John Donatich John Donatich is the Director of Yale University Press. Passage 9: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Passage 10: Eyes of Fate Eyes of Fate is a 1933 British sports fantasy film directed by Ivar Campbell and starring Allan Jeayes, Valerie Hobson and Terence De Marney. It is a quota quickie, made at Shepperton Studios. It is also known by the alternative title of All the Winners. A bookmaker seems to have struck it lucky when he comes across a newspaper containing the next day's horse racing results, but the paper also contains some more unsettling news. Question: Which country the director of film Eyes Of Fate is from? Answer: New Zealand
{ "task_name": "2WikiMultihopQA" }
Passage 1: Alexander Courage Alexander Mair" Sandy" Courage Jr.( December 10, 1919 May 15, 2008) was an American orchestrator, arranger, and composer of music, primarily for television and film. He is best known as the composer of the theme music for the original" Star Trek" series. Passage 2: Walter Robinson (composer) Walter Robinson is an African American composer of the late 20th century. He is most notable for his 1977 song" Harriet Tubman", which has been recorded by folk musicians such as Holly Near, John McCutcheon, and others. He is also the composer of several operas. Passage 3: Alexandru Cristea Alexandru Cristea( 1890 – 1942) was the composer of the music for" Limba Noastră", current national anthem of Moldova. Passage 4: David Bowie David Robert Jones (8 January 1947 – 10 January 2016), known professionally as David Bowie , was an English singer-songwriter and actor. He was a leading figure in the music industry and is considered one of the most influential musicians of the 20th century, acclaimed by critics and musicians, particularly for his innovative work during the 1970s. His career was marked by reinvention and visual presentation, with his music and stagecraft having a significant impact on popular music. During his lifetime, his record sales, estimated at 140 million albums worldwide, made him one of the world's best-selling music artists. In the UK, he was awarded ten platinum album certifications, eleven gold and eight silver, and released eleven number-one albums. In the US, he received five platinum and nine gold certifications. He was inducted into the Rock and Roll Hall of Fame in 1996. Born in Brixton, South London, Bowie developed an interest in music as a child, eventually studying art, music and design before embarking on a professional career as a musician in 1963. "Space Oddity" became his first top-five entry on the UK Singles Chart after its release in July 1969. After a period of experimentation, he re-emerged in 1972 during the glam rock era with his flamboyant and androgynous alter ego Ziggy Stardust. The character was spearheaded by the success of his single "Starman" and album " The Rise and Fall of Ziggy Stardust and the Spiders from Mars", which won him widespread popularity. In 1975, Bowie's style shifted radically towards a sound he characterised as "plastic soul", initially alienating many of his UK devotees but garnering him his first major US crossover success with the number-one single "Fame" and the album "Young Americans". In 1976, Bowie starred in the cult film " The Man Who Fell to Earth", directed by Nicolas Roeg, and released "Station to Station". The following year, he further confounded musical expectations with the electronic-inflected album "Low" (1977), the first of three collaborations with Brian Eno that came to be known as the "Berlin Trilogy"Heroes (1977) and "Lodger" (1979) followed; each album reached the UK top five and received lasting critical praise. After uneven commercial success in the late 1970s, Bowie had UK number ones with the 1980 single "Ashes to Ashes", its parent album "Scary Monsters (and Super Creeps)", and "Under Pressure", a 1981 collaboration with Queen. He reached his commercial peak in 1983 with "Let's Dance"; the album's title track topped both UK and US charts. Throughout the 1990s and 2000s, Bowie continued to experiment with musical styles, including industrial and jungle. He also continued acting; his roles included Major Jack Celliers in "Merry Christmas, Mr. Lawrence" (1983), Jareth the Goblin King in "Labyrinth" (1986), Pontius Pilate in "The Last Temptation of Christ" (1988), and Nikola Tesla in "The Prestige" (2006), among other film and television appearances and cameos. He stopped touring after 2004 and his last live performance was at a charity event in 2006. In 2013, Bowie returned from a decade-long recording hiatus with "The Next Day." He remained musically active until he died of liver cancer at his home in New York City, two days after his 69th birthday and the release of his final album, "Blackstar" (2016). Passage 5: Ami Banglay Gaan Gai " Ami Banglay Gaan Gai" is a patriotic song by Bangladeshi poet and composer Pratul Mukhopadhyay. He is also the composer and original singer of the song. The song was nominated as one the most popular songs on March, 2006. Passage 6: Petrus de Domarto Petrus de Domarto( fl. c. 1445– 1455) was a Franco- Flemish composer of the Renaissance. He was a contemporary and probable acquaintance of Ockeghem, and was the composer of at least one of the first unified mass cycles to be written in continental Europe. Passage 7: Michelangelo Faggioli Michelangelo Faggioli( 1666–1733) was an Italian lawyer and celebrated amateur composer of humorous cantatas in Neapolitan dialect. A founder of a new genre of Neapolitan comedy, he was the composer of the opera buffa" La Cilla" in 1706. Passage 8: Alonso Mudarra Alonso Mudarra( c. 1510 – April 1, 1580) was a Spanish composer of the Renaissance, and also played the vihuela, a guitar- shaped string instrument. He was an innovative composer of instrumental music as well as songs, and was the composer of the earliest surviving music for the guitar. Passage 9: Tarcisio Fusco Tarcisio Fusco was an Italian composer of film scores. He was the brother of the composer Giovanni Fusco and the uncle of operatic soprano Cecilia Fusco. Passage 10: The Jean Genie "The Jean Genie" is a song by David Bowie, originally released as a single in November 1972. According to Bowie, it was "a smorgasbord of imagined Americana", with a protagonist inspired by Iggy Pop, and the title being an allusion to author Jean Genet. One of Bowie's most famous tracks, it was the lead single for the album "Aladdin Sane" (1973). Promoted with a film clip featuring Andy Warhol associate Cyrinda Foxe, it peaked at No. 2 on the UK Singles Chart. Question: Where was the composer of song The Jean Genie born? Answer: Brixton
{ "task_name": "2WikiMultihopQA" }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using Microsoft.Xna.Framework; using QEngine.Physics.Dynamics.Solver; using QEngine.Physics.Shared; using QEngine.Physics.Utilities; namespace QEngine.Physics.Dynamics.Joints { /// <summary> /// A motor joint is used to control the relative motion /// between two bodies. A typical usage is to control the movement /// of a dynamic body with respect to the ground. /// </summary> public class MotorJoint : Joint { private float _angularError; private float _angularImpulse; private float _angularMass; private float _angularOffset; // Solver temp private int _indexA; private int _indexB; private float _invIA; private float _invIB; private float _invMassA; private float _invMassB; private Vector2 _linearError; private Vector2 _linearImpulse; private Mat22 _linearMass; // Solver shared private Vector2 _linearOffset; private Vector2 _localCenterA; private Vector2 _localCenterB; private float _maxForce; private float _maxTorque; private Vector2 _rA; private Vector2 _rB; internal MotorJoint() { JointType = JointType.Motor; } /// <summary> /// Constructor for MotorJoint. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public MotorJoint(Body bodyA, Body bodyB, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Motor; Vector2 xB = BodyB.Position; if (useWorldCoordinates) _linearOffset = BodyA.GetLocalPoint(xB); else _linearOffset = xB; //Defaults //_angularOffset = 0.0f; _maxForce = 1.0f; _maxTorque = 1.0f; CorrectionFactor = 0.3f; _angularOffset = BodyB.Rotation - BodyA.Rotation; } public override Vector2 WorldAnchorA { get { return BodyA.Position; } set { System.Diagnostics.Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public override Vector2 WorldAnchorB { get { return BodyB.Position; } set { System.Diagnostics.Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// The maximum amount of force that can be applied to BodyA /// </summary> public float MaxForce { set { System.Diagnostics.Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxForce = value; } get { return _maxForce; } } /// <summary> /// The maximum amount of torque that can be applied to BodyA /// </summary> public float MaxTorque { set { System.Diagnostics.Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxTorque = value; } get { return _maxTorque; } } /// <summary> /// The linear (translation) offset. /// </summary> public Vector2 LinearOffset { set { if (_linearOffset.X != value.X || _linearOffset.Y != value.Y) { WakeBodies(); _linearOffset = value; } } get { return _linearOffset; } } /// <summary> /// Get or set the angular offset. /// </summary> public float AngularOffset { set { if (_angularOffset != value) { WakeBodies(); _angularOffset = value; } } get { return _angularOffset; } } //Velcro note: Used for serialization. internal float CorrectionFactor { get; set; } public override Vector2 GetReactionForce(float invDt) { return invDt * _linearImpulse; } public override float GetReactionTorque(float invDt) { return invDt * _angularImpulse; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; Vector2 cA = data.Positions[_indexA].C; float aA = data.Positions[_indexA].A; Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 cB = data.Positions[_indexB].C; float aB = data.Positions[_indexB].A; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; Rot qA = new Rot(aA); Rot qB = new Rot(aB); // Compute the effective mass matrix. _rA = MathUtils.Mul(qA, -_localCenterA); _rB = MathUtils.Mul(qB, -_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Mat22 K = new Mat22(); K.ex.X = mA + mB + iA * _rA.Y * _rA.Y + iB * _rB.Y * _rB.Y; K.ex.Y = -iA * _rA.X * _rA.Y - iB * _rB.X * _rB.Y; K.ey.X = K.ex.Y; K.ey.Y = mA + mB + iA * _rA.X * _rA.X + iB * _rB.X * _rB.X; _linearMass = K.Inverse; _angularMass = iA + iB; if (_angularMass > 0.0f) { _angularMass = 1.0f / _angularMass; } _linearError = cB + _rB - cA - _rA - MathUtils.Mul(qA, _linearOffset); _angularError = aB - aA - _angularOffset; if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _linearImpulse *= data.Step.dtRatio; _angularImpulse *= data.Step.dtRatio; Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y); vA -= mA * P; wA -= iA * (MathUtils.Cross(_rA, P) + _angularImpulse); vB += mB * P; wB += iB * (MathUtils.Cross(_rB, P) + _angularImpulse); } else { _linearImpulse = Vector2.Zero; _angularImpulse = 0.0f; } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; float h = data.Step.dt; float inv_h = data.Step.inv_dt; // Solve angular friction { float Cdot = wB - wA + inv_h * CorrectionFactor * _angularError; float impulse = -_angularMass * Cdot; float oldImpulse = _angularImpulse; float maxImpulse = h * _maxTorque; _angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = _angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { Vector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA) + inv_h * CorrectionFactor * _linearError; Vector2 impulse = -MathUtils.Mul(ref _linearMass, ref Cdot); Vector2 oldImpulse = _linearImpulse; _linearImpulse += impulse; float maxImpulse = h * _maxForce; if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { _linearImpulse.Normalize(); _linearImpulse *= maxImpulse; } impulse = _linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * MathUtils.Cross(_rA, impulse); vB += mB * impulse; wB += iB * MathUtils.Cross(_rB, impulse); } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { return true; } } }
{ "task_name": "lcc" }
Passage 1: Wayne State University Wayne State University (WSU) is a public research university located in Detroit, Michigan. Founded in 1868, WSU consists of 13 schools and colleges offering nearly 350 programs to more than 27,000 graduate and undergraduate students. Wayne State University is Michigan's third-largest university and one of the 100 largest universities in the United States. Passage 2: Bohol Island State University The Bohol Island State University (BISU), formerly the Central Visayas State College of Agriculture, Forestry and Technology (CVSCAFT), is a public institution of higher learning in Bohol, Philippines. The institution operates campuses spread throughout the province, with the main campus in Tagbilaran city, Bohol. Passage 3: Tapan K. Datta Tapan K. Datta is a Wayne State University civil engineering professor and researcher who highly specializes in transportation engineering and safety. After receiving his early schooling, undergraduate degrees, and field experience in Calcutta, India, he moved to the United States to complete his master’s and doctoral degrees. While in Detroit, MI, he worked for and later owned Goodell Grivas, Inc., a structural engineering consulting firm, and became a full-time faculty member at Wayne State University in 1973. His most notable contributions include work on the roof of Cobo Hall, in Detroit, MI, and the steel structural work done on Jacobs Field (now Progressive Field) in Cleveland, OH. Dr. Datta has also claimed to be the inventor of the double-drive thru at fast food establishments. Dr. Datta also founded the Transportation Research Group at Wayne State University; this group is composed of undergraduate and graduate students that complete transportation-related research grant projects for the State of Michigan. Passage 4: State University of New York at Oneonta The State University of New York College at Oneonta (more commonly known as SUNY Oneonta, and also called Oneonta State, SUCO, and O-State) is a four-year liberal arts college in Oneonta, New York, United States, with approximately 10,000 students. The college offers a wide variety of bachelor's degree programs and a number of graduate degrees. Many academic programs at SUNY Oneonta hold national accreditations, including programs in Business Economics, Education, Music Industry, Human Ecology and Theatre. SUNY Oneonta is ranked No. 12 on the 2017 "U.S. News and World Report" list of "" Best Public Colleges in the North" and was named to the Kiplinger's Personal Finance magazine list of "100 Best Values in Public Colleges" for 10 years running; In 2011, the Carnegie Foundation for the Advancement of Teaching conferred upon SUNY Oneonta its Community Engagement Classification "in recognition of the college's civic partnerships and successful efforts to integrate service activities into its curriculum." Passage 5: The Frederick Linsell House The Frederick Linsell House of Fine Performing and Communication Arts is a landmark building on the campus of Wayne State University in Detroit, Michigan. Originally located on the corner of 2nd and Putnam, the two-story Georgian style home was constructed for Frederick and Rosa Linsell in 1904, by architect John C. Stahl at a cost of $9,000. The Linsells lived there for 10 years before selling it. After serving as a home for two more families, the building was bought by the Detroit Board of Education in the 1930s. In 1939 the building became the Women’s Study Building for the university. It was the only building of 16 on its block that survived the expansion of Wayne State’s campus in the mid 1900s. In 1956 the Board of Education donated the Linsell House to the university and it became the office for the School of Business, and later the Biology Department. In 1987 the house was restored and turned into the Dean’s Office for the College of Fine Performing and Communication Arts. The thirteen-room house is now located at 5104 Gullen Mall, in the middle of the Wayne State campus. Passage 6: Wayne State Warriors football The Wayne State Warriors football team is the college football team at Wayne State University in Detroit, Michigan. The Wayne State football team played their first game in October 1918. The Wayne State Warriors have competed in the Great Lakes Intercollegiate Athletic Conference since 1999 (and previously from 1975-1989), and are currently a Division II member of the National Collegiate Athletic Association (NCAA). Wayne State plays their home games at Tom Adams Field at Wayne State Stadium. All Wayne State games are broadcast on WDTK radio. Passage 7: List of state universities in the United States In the United States, a state college or state university is one of the public colleges or universities funded by or associated with the state government. In some cases, these institutions of higher learning are part of a state university system, while in other cases they are not. Several U.S. territories also administer public colleges and universities. The U.S. federal government does not run colleges or universities except for the service academies, the Community College of the Air Force, the Naval Postgraduate School, the Air Force Institute of Technology, the Uniformed Services University of the Health Sciences, military war colleges and staff colleges, and Haskell Indian Nations University. Additionally, Georgetown University, Gallaudet University, Howard University, and American University are private universities that are federally chartered. However, the federal government does make grants to state universities. Passage 8: Wayne State University College of Engineering The Wayne State University College of Engineering is responsible for all engineering related programs at Wayne State University. With alumni of the college totaling over 25,000, it is one of the premier engineering colleges in Michigan along with being in the top 30% of the country. Founded in 1933, the College of Engineering has grown to include a variety of programs ranging from civil engineering, biomedical engineering, and many others. It is one of only 24 PACE partner labs in the country as well as being a leader in biomedical engineering. The College of Engineering is located in the Wayne State campus in Detroit. It is located in the College of Engineering building which is shared with the Danto Engineering Development Center. The current Dean of Engineering is Dr. Farshad Fotouhi. Passage 9: Nebraska State College System The Nebraska State College System is the governing body for Nebraska's three public colleges (Chadron State College, Peru State College and Wayne State College) that are not part of the University of Nebraska System. Passage 10: Detroit Medical Center The Detroit Medical Center (DMC), located in Midtown Detroit, Michigan, is an alliance of hospitals that encompasses over 2,000 licensed beds, 3,000 affiliated physicians and over 12,000 employees. The DMC is affiliated with the medical schools of Wayne State University and Michigan State University. Detroit Medical Center hospitals are staffed by physicians from the Michigan State University College of Osteopathic Medicine, which is ranked 17th in the nation in primary care, and the Wayne State University School of Medicine, the largest single-campus medical school in the United States, and the nation’s fourth largest medical school overall. Detroit Medical Center is fully accredited by the Joint Commission on Accreditation of Healthcare Organizations. Question: Are Bohol Island State University and Wayne State University both public colleges? Answer: yes
{ "task_name": "hotpotqa" }
package org.mitre.synthea.engine; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import java.io.File; import java.io.FileReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import org.mitre.synthea.modules.CardiovascularDiseaseModule; import org.mitre.synthea.modules.EncounterModule; import org.mitre.synthea.modules.HealthInsuranceModule; import org.mitre.synthea.modules.LifecycleModule; import org.mitre.synthea.modules.QualityOfLifeModule; import org.mitre.synthea.world.agents.Person; /** * Module represents the entry point of a generic module. * * <p>The `modules` map is the static list of generic modules. It is loaded once per process, * and the list of modules is shared between the generated population. Because we share modules * across the population, it is important that States are cloned before they are executed. * This keeps the "master" copy of the module clean. */ public class Module { private static final Map<String, Module> modules = loadModules(); private static Map<String, Module> loadModules() { Map<String, Module> retVal = new ConcurrentHashMap<String, Module>(); retVal.put("Lifecycle", new LifecycleModule()); retVal.put("Cardiovascular Disease", new CardiovascularDiseaseModule()); retVal.put("Quality Of Life", new QualityOfLifeModule()); retVal.put("Health Insurance", new HealthInsuranceModule()); try { URL modulesFolder = ClassLoader.getSystemClassLoader().getResource("modules"); Path path = Paths.get(modulesFolder.toURI()); Files.walk(path, Integer.MAX_VALUE).filter(Files::isReadable).filter(Files::isRegularFile) .filter(p -> p.toString().endsWith(".json")).forEach(t -> { try { Module module = loadFile(t, path); String relativePath = relativePath(t, path); retVal.put(relativePath, module); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }); } catch (Exception e) { e.printStackTrace(); } System.out.format("Loaded %d modules.\n", retVal.size()); return retVal; } private static String relativePath(Path filePath, Path modulesFolder) { String folderString = Matcher.quoteReplacement(modulesFolder.toString() + File.separator); return filePath.toString().replaceFirst(folderString, "").replaceFirst(".json", "") .replace("\\", "/"); } public static Module loadFile(Path path, Path modulesFolder) throws Exception { System.out.format("Loading %s\n", path.toString()); boolean submodule = !path.getParent().equals(modulesFolder); JsonObject object = null; FileReader fileReader = null; JsonReader reader = null; fileReader = new FileReader(path.toString()); reader = new JsonReader(fileReader); JsonParser parser = new JsonParser(); object = parser.parse(reader).getAsJsonObject(); fileReader.close(); reader.close(); return new Module(object, submodule); } public static String[] getModuleNames() { return modules.keySet().toArray(new String[modules.size()]); } /** * @return a list of top-level modules. Submodules are not included. */ public static List<Module> getModules() { List<Module> list = new ArrayList<Module>(); modules.forEach((k, v) -> { if (!v.submodule) { list.add(v); } }); return list; } /** * @param path * : the relative path of the module, without the root or ".json" file extension. For * example, "medications/otc_antihistamine" or "appendicitis". * @return module : the given module */ public static Module getModuleByPath(String path) { return modules.get(path); } public String name; public boolean submodule; public List<String> remarks; private Map<String, State> states; protected Module() { // no-args constructor only allowed to be used by subclasses } public Module(JsonObject definition, boolean submodule) throws Exception { name = String.format("%s Module", definition.get("name").getAsString()); this.submodule = submodule; remarks = new ArrayList<String>(); if (definition.has("remarks")) { JsonElement jsonRemarks = definition.get("remarks"); for (JsonElement value : jsonRemarks.getAsJsonArray()) { remarks.add(value.getAsString()); } } JsonObject jsonStates = definition.get("states").getAsJsonObject(); states = new ConcurrentHashMap<String, State>(); for (Entry<String, JsonElement> entry : jsonStates.entrySet()) { State state = State.build(this, entry.getKey(), entry.getValue().getAsJsonObject()); states.put(entry.getKey(), state); } } /** * Process this Module with the given Person at the specified time within the simulation. * * @param person * : the person being simulated * @param time * : the date within the simulated world * @return completed : whether or not this Module completed. */ @SuppressWarnings("unchecked") public boolean process(Person person, long time) { person.history = null; // what current state is this person in? if (!person.attributes.containsKey(this.name)) { person.history = new LinkedList<State>(); person.history.add(initialState()); person.attributes.put(this.name, person.history); } person.history = (List<State>) person.attributes.get(this.name); String activeKey = EncounterModule.ACTIVE_WELLNESS_ENCOUNTER + " " + this.name; if (person.attributes.containsKey(EncounterModule.ACTIVE_WELLNESS_ENCOUNTER)) { person.attributes.put(activeKey, true); } State current = person.history.get(0); // System.out.println(" Resuming at " + current.name); // process the current state, // looping until module is finished, // probably more than one state String nextStateName = null; while (current.run(person, time)) { Long exited = current.exited; nextStateName = current.transition(person, time); // System.out.println(" Transitioning to " + nextStateName); current = states.get(nextStateName).clone(); // clone the state so we don't dirty the original person.history.add(0, current); if (exited != null && exited < time) { // This must be a delay state that expired between cycles, so temporarily rewind time process(person, exited); current = person.history.get(0); } } person.attributes.remove(activeKey); return (current instanceof State.Terminal); } private State initialState() { return states.get("Initial"); // all Initial states have name Initial } public State getState(String name) { return states.get(name); } /** * Get a collection of the names of all the states this Module contains. * * @return set of all state names, or empty set if this is a non-GMF module */ public Collection<String> getStateNames() { if (states == null) { // ex, if this is a non-GMF module return Collections.emptySet(); } return states.keySet(); } }
{ "task_name": "lcc" }
package org.apache.mesos.hdfs; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.mesos.Protos; import org.apache.mesos.SchedulerDriver; import org.apache.mesos.hdfs.config.HdfsFrameworkConfig; import org.apache.mesos.hdfs.scheduler.HdfsScheduler; import org.apache.mesos.hdfs.state.AcquisitionPhase; import org.apache.mesos.hdfs.state.LiveState; import org.apache.mesos.hdfs.state.IPersistentStateStore; import org.apache.mesos.hdfs.util.DnsResolver; import org.apache.mesos.hdfs.util.HDFSConstants; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.HashMap; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @SuppressWarnings("unchecked") public class TestScheduler { private final HdfsFrameworkConfig hdfsFrameworkConfig = new HdfsFrameworkConfig(new Configuration()); @Mock SchedulerDriver driver; @Mock IPersistentStateStore persistenceStore; @Mock LiveState liveState; @Mock DnsResolver dnsResolver; @Captor ArgumentCaptor<Collection<Protos.TaskInfo>> taskInfosCapture; HdfsScheduler scheduler; @Test public void statusUpdateWasStagingNowRunning() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.JOURNAL_NODES); Protos.TaskID taskId = createTaskId("1"); scheduler.statusUpdate(driver, createTaskStatus(taskId, Protos.TaskState.TASK_RUNNING)); verify(liveState).removeStagingTask(taskId); } @Test public void statusUpdateTransitionFromAcquiringJournalNodesToStartingNameNodes() { Protos.TaskID taskId = createTaskId("1"); when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.JOURNAL_NODES); when(liveState.getJournalNodeSize()).thenReturn(3); scheduler.statusUpdate(driver, createTaskStatus(taskId, Protos.TaskState.TASK_RUNNING)); verify(liveState).transitionTo(AcquisitionPhase.START_NAME_NODES); } @Test public void statusUpdateAcquiringJournalNodesNotEnoughYet() { Protos.TaskID taskId = createTaskId("1"); when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.JOURNAL_NODES); when(liveState.getJournalNodeSize()).thenReturn(2); scheduler.statusUpdate(driver, createTaskStatus(taskId, Protos.TaskState.TASK_RUNNING)); verify(liveState, never()).transitionTo(AcquisitionPhase.START_NAME_NODES); } @Test public void statusUpdateTransitionFromStartingNameNodesToFormateNameNodes() { Protos.TaskID taskId = createTaskId(HDFSConstants.NAME_NODE_TASKID + "1"); Protos.SlaveID slaveId = createSlaveId("1"); when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.START_NAME_NODES); when(liveState.getNameNodeSize()).thenReturn(2); when(liveState.getJournalNodeSize()).thenReturn(hdfsFrameworkConfig.getJournalNodeCount()); when(liveState.getFirstNameNodeTaskId()).thenReturn(taskId); when(liveState.getFirstNameNodeSlaveId()).thenReturn(slaveId); scheduler.statusUpdate(driver, createTaskStatus(taskId, Protos.TaskState.TASK_RUNNING)); verify(liveState).transitionTo(AcquisitionPhase.FORMAT_NAME_NODES); } @Test public void statusUpdateTransitionFromFormatNameNodesToDataNodes() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.FORMAT_NAME_NODES); when(liveState.getJournalNodeSize()).thenReturn(hdfsFrameworkConfig.getJournalNodeCount()); when(liveState.getNameNodeSize()).thenReturn(HDFSConstants.TOTAL_NAME_NODES); when(liveState.isNameNode1Initialized()).thenReturn(true); when(liveState.isNameNode2Initialized()).thenReturn(true); scheduler.statusUpdate( driver, createTaskStatus(createTaskId(HDFSConstants.NAME_NODE_TASKID), Protos.TaskState.TASK_RUNNING)); verify(liveState).transitionTo(AcquisitionPhase.DATA_NODES); } @Test public void statusUpdateAquiringDataNodesJustStays() { Protos.TaskID taskId = createTaskId("1"); when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.DATA_NODES); scheduler.statusUpdate(driver, createTaskStatus(taskId, Protos.TaskState.TASK_RUNNING)); verify(liveState, never()).transitionTo(any(AcquisitionPhase.class)); } @Test public void startsAJournalNodeWhenGivenAnOffer() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.JOURNAL_NODES); scheduler.resourceOffers(driver, Lists.newArrayList(createTestOfferWithResources(0, 2, 2048))); verify(driver, times(1)).launchTasks(anyList(), taskInfosCapture.capture()); assertEquals(1, taskInfosCapture.getValue().size()); } @Test public void launchesOnlyNeededNumberOfJournalNodes() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.JOURNAL_NODES); HashMap<String, String> journalNodes = new HashMap<String, String>(); journalNodes.put("host1", "journalnode1"); journalNodes.put("host2", "journalnode2"); journalNodes.put("host3", "journalnode3"); when(persistenceStore.getJournalNodes()).thenReturn(journalNodes); scheduler.resourceOffers(driver, Lists.newArrayList(createTestOffer(0))); verify(driver, never()).launchTasks(anyList(), anyList()); } @Test public void launchesNamenodeWhenInNamenode1Phase() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.START_NAME_NODES); when(persistenceStore.getNameNodeTaskNames()).thenReturn(new HashMap<String, String>()); when(persistenceStore.journalNodeRunningOnSlave("host0")).thenReturn(true); when(dnsResolver.journalNodesResolvable()).thenReturn(true); scheduler.resourceOffers(driver, Lists.newArrayList(createTestOffer(0))); verify(driver, times(1)).launchTasks(anyList(), taskInfosCapture.capture()); assertTrue(taskInfosCapture.getValue().size() == 2); Iterator<Protos.TaskInfo> taskInfoIterator = taskInfosCapture.getValue().iterator(); String firstTask = taskInfoIterator.next().getName(); assertTrue(firstTask.contains(HDFSConstants.NAME_NODE_ID) || firstTask.contains(HDFSConstants.ZKFC_NODE_ID)); String secondTask = taskInfoIterator.next().getName(); assertTrue(secondTask.contains(HDFSConstants.NAME_NODE_ID) || secondTask.contains(HDFSConstants.ZKFC_NODE_ID)); } @Test public void declinesAnyOffersPastWhatItNeeds() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.DATA_NODES); scheduler.resourceOffers(driver, Lists.newArrayList( createTestOffer(0), createTestOffer(1), createTestOffer(2), createTestOffer(3) )); verify(driver, times(3)).declineOffer(any(Protos.OfferID.class)); } @Test public void launchesDataNodesWhenInDatanodesPhase() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.DATA_NODES); scheduler.resourceOffers(driver, Lists.newArrayList( createTestOffer(0) ) ); verify(driver, times(1)).launchTasks(anyList(), taskInfosCapture.capture()); Protos.TaskInfo taskInfo = taskInfosCapture.getValue().iterator().next(); assertTrue(taskInfo.getName().contains(HDFSConstants.DATA_NODE_ID)); } @Test public void removesTerminalTasksFromLiveState() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.DATA_NODES); scheduler.statusUpdate(driver, createTaskStatus(createTaskId("0"), Protos.TaskState.TASK_FAILED)); scheduler.statusUpdate(driver, createTaskStatus(createTaskId("1"), Protos.TaskState.TASK_FINISHED)); scheduler.statusUpdate(driver, createTaskStatus(createTaskId("2"), Protos.TaskState.TASK_KILLED)); scheduler.statusUpdate(driver, createTaskStatus(createTaskId("3"), Protos.TaskState.TASK_LOST)); verify(liveState, times(4)).removeStagingTask(any(Protos.TaskID.class)); verify(liveState, times(4)).removeRunningTask(any(Protos.TaskID.class)); } @Test public void declinesOffersWithNotEnoughResources() { when(liveState.getCurrentAcquisitionPhase()).thenReturn(AcquisitionPhase.DATA_NODES); Protos.Offer offer = createTestOfferWithResources(0, 0.1, 64); scheduler.resourceOffers(driver, Lists.newArrayList(offer)); verify(driver, times(1)).declineOffer(offer.getId()); } @Before public void setup() { MockitoAnnotations.initMocks(this); this.scheduler = new HdfsScheduler(hdfsFrameworkConfig, liveState, persistenceStore); } private Protos.TaskID createTaskId(String id) { return Protos.TaskID.newBuilder().setValue(id).build(); } private Protos.OfferID createTestOfferId(int instanceNumber) { return Protos.OfferID.newBuilder().setValue("offer" + instanceNumber).build(); } private Protos.SlaveID createSlaveId(String slaveId) { return Protos.SlaveID.newBuilder().setValue(slaveId).build(); } private Protos.ExecutorID createExecutorId(String executorId) { return Protos.ExecutorID.newBuilder().setValue(executorId).build(); } private Protos.Offer createTestOffer(int instanceNumber) { return Protos.Offer.newBuilder() .setId(createTestOfferId(instanceNumber)) .setFrameworkId(Protos.FrameworkID.newBuilder().setValue("framework1").build()) .setSlaveId(Protos.SlaveID.newBuilder().setValue("slave" + instanceNumber).build()) .setHostname("host" + instanceNumber) .build(); } private Protos.Offer createTestOfferWithResources(int instanceNumber, double cpus, int mem) { return Protos.Offer.newBuilder() .setId(createTestOfferId(instanceNumber)) .setFrameworkId(Protos.FrameworkID.newBuilder().setValue("framework1").build()) .setSlaveId(Protos.SlaveID.newBuilder().setValue("slave" + instanceNumber).build()) .setHostname("host" + instanceNumber) .addAllResources(Arrays.asList( Protos.Resource.newBuilder() .setName("cpus") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder() .setValue(cpus).build()) .setRole("*") .build(), Protos.Resource.newBuilder() .setName("mem") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder() .setValue(mem).build()) .setRole("*") .build())) .build(); } private Protos.TaskStatus createTaskStatus(Protos.TaskID taskID, Protos.TaskState state) { return Protos.TaskStatus.newBuilder() .setTaskId(taskID) .setState(state) .setSlaveId(Protos.SlaveID.newBuilder().setValue("slave").build()) .setMessage("From Test") .build(); } }
{ "task_name": "lcc" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Surface; using Microsoft.Surface.Presentation; using Microsoft.Surface.Presentation.Controls; using Microsoft.Surface.Presentation.Input; using System.Threading; using Table; using System.ServiceModel; using System.Diagnostics; using Reflectable_v2; using System.IO; namespace Table { [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false)] public partial class MainWindow : SurfaceWindow, ITableService { private const int MAX_CLIENTS = 4; private ServiceHost serviceHost; private Dictionary<int, ICallbackContract> tablets; private Round currentRound; private bool roundInProgress; private bool gameStarted; private CameraCapture camera; private DateTime startTime; private List<Press> presses; private PanopticonProcessor panopticonProcessor; private DateTime lastPercentageUpdate; private FileDownloadService fileDownloadService; private bool researchQuestionSet; private Dictionary<Round.RoundId, Round> rounds; public MainWindow() { rounds = new Dictionary<Round.RoundId, Round>() { { Round.RoundId.PAPER_DIVERGE, new Round(Round.RoundId.PAPER_DIVERGE, 1, Properties.Settings.Default.Round_1_Time, Properties.Settings.Default.Round_1_Instructions) }, { Round.RoundId.PAPER_CONVERGE, new Round(Round.RoundId.PAPER_CONVERGE, 2, Properties.Settings.Default.Round_2_Time, Properties.Settings.Default.Round_2_Instructions) }, { Round.RoundId.PAPER_TRANSCEND, new Round(Round.RoundId.PAPER_TRANSCEND, 3, Properties.Settings.Default.Round_3_Time, Properties.Settings.Default.Round_3_Instructions) }, { Round.RoundId.VIDEO_BROWSE, new Round(Round.RoundId.VIDEO_BROWSE, 4, Properties.Settings.Default.Round_4_Time, Properties.Settings.Default.Round_4_Instructions) }, { Round.RoundId.RESEARCH_QUESTION, new Round(Round.RoundId.RESEARCH_QUESTION, 0, TimeSpan.Zero, "") }, { Round.RoundId.VIDEO_DIVERGE, new Round(Round.RoundId.VIDEO_DIVERGE, 5, Properties.Settings.Default.Round_5_Time, Properties.Settings.Default.Round_5_Instructions) }, { Round.RoundId.VIDEO_CONVERGE, new Round(Round.RoundId.VIDEO_CONVERGE, 6, Properties.Settings.Default.Round_6_Time, Properties.Settings.Default.Round_6_Instructions) }, { Round.RoundId.COMPLETE, new Round(Round.RoundId.COMPLETE, 0, new TimeSpan(), Properties.Settings.Default.Complete_Instructions) } }; currentRound = rounds[Round.RoundId.PAPER_DIVERGE]; tablets = new Dictionary<int, ICallbackContract>(); roundInProgress = false; gameStarted = false; camera = new CameraCapture(); presses = new List<Press>(); lastPercentageUpdate = DateTime.UtcNow; fileDownloadService = new FileDownloadService(); researchQuestionSet = false; panopticonProcessor = new PanopticonProcessor(); panopticonProcessor.PercentageChanged += new PanopticonProcessor.PercentageChangedEventHandler(panopticonProcessor_PercentageChanged); panopticonProcessor.ProcessingCompleted += new PanopticonProcessor.ProcessingCompletedEventHandler(panopticonProcessor_ProcessingCompleted); panopticonProcessor.ProcessingFailed += new PanopticonProcessor.ProcessingFailedEventHandler(panopticonProcessor_ProcessingFailed); NetTcpBinding serviceBinding = new NetTcpBinding(SecurityMode.None); serviceBinding.ReceiveTimeout = TimeSpan.MaxValue; serviceBinding.SendTimeout = TimeSpan.MaxValue; serviceHost = new ServiceHost(this); serviceHost.AddServiceEndpoint(typeof(ITableService), serviceBinding, "net.tcp://localhost:8010"); serviceHost.Open(); Loaded += new RoutedEventHandler(MainWindow_Loaded); InitializeComponent(); } public void Disconnect() { serviceHost.Close(); fileDownloadService.Close(); } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { Window w = App.Current.MainWindow; #if DEBUG w.WindowState = WindowState.Normal; w.WindowStyle = WindowStyle.ThreeDBorderWindow; #else w.WindowStyle = WindowStyle.None; w.WindowState = WindowState.Maximized; w.ResizeMode = ResizeMode.NoResize; w.Topmost = true; #endif } protected override void OnClosed(EventArgs e) { base.OnClosed(e); if (camera.IsCapturing) { camera.StopCapture(); } } private void StartGame() { camera.StartCapture(); startTime = DateTime.UtcNow; gameStarted = true; } private void panopticonProcessor_ProcessingCompleted(object sender) { fileDownloadService.PanopticonVideoFile = panopticonProcessor.Filename; tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.PanopticonCompleted(); } catch (CommunicationObjectAbortedException) { } }); } private void panopticonProcessor_PercentageChanged(object sender, int percentage) { tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.PanopticonPercentageChanged(percentage); } catch (CommunicationObjectAbortedException) { } }); } void panopticonProcessor_ProcessingFailed(object sender, Exception e) { StartPanopticonProcessing(); } private static Color CovertColor(System.Drawing.Color c) { return Color.FromArgb(c.A, c.R, c.G, c.B); } public static Color GetColorFromUser(User u) { Color c; switch (u.Id) { case 0: c = CovertColor(Properties.Settings.Default.User0Colour); break; case 1: c = CovertColor(Properties.Settings.Default.User1Colour); break; case 2: c = CovertColor(Properties.Settings.Default.User2Colour); break; case 3: c = CovertColor(Properties.Settings.Default.User3Colour); break; default: c = Colors.White; break; } return c; } private void StartPanopticonProcessing() { Thread t = new Thread(() => { camera.StopCapture(); fileDownloadService.VideoFile = camera.VideoFileName; panopticonProcessor.ProcessFile(camera.VideoFileName); }); t.Start(); } #region WebService public void Register(User u) { try { ICallbackContract tablet = OperationContext.Current.GetCallbackChannel<ICallbackContract>(); if (tablets.ContainsKey(u.Id)) { tablets.Remove(u.Id); } tablet.SetUserColor(GetColorFromUser(u)); tablets[u.Id] = tablet; tablet.SetRound(currentRound); } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void RoundComplete(Round r) { try { if (r.Id == Round.RoundId.PAPER_TRANSCEND) { StartPanopticonProcessing(); } int i = (int)(r.Id + 1); Round.RoundId newId = (Round.RoundId)(i % Round.NUM_ROUNDS); if (newId != currentRound.Id) { currentRound = rounds[newId]; roundInProgress = false; bool restart = false; switch (currentRound.Id) { case Round.RoundId.VIDEO_BROWSE: Dispatcher.BeginInvoke(new Action(() => { Tabletop.VideoFile = camera.VideoFileName; Tabletop.Presses = presses; Tabletop.Visibility = Visibility.Visible; Screensaver.Visibility = Visibility.Hidden; })); break; case Round.RoundId.COMPLETE: restart = true; break; } tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.SetRound(currentRound); } catch (CommunicationObjectAbortedException) { } }); if (restart) { Dispatcher.BeginInvoke(new Action(() => { Disconnect(); App.Restart(); })); } } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void RequestStartRound() { try { if (!roundInProgress) { roundInProgress = true; if (currentRound.Id == Round.RoundId.PAPER_DIVERGE && !gameStarted) { StartGame(); } DateTime startTime = DateTime.UtcNow; tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.StartRound(startTime); } catch (CommunicationObjectAbortedException) { } }); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void ButtonPress(User u) { try { if (gameStarted && roundInProgress) { Color c = GetColorFromUser(u); u.Color = c; TimeSpan end = DateTime.UtcNow - startTime; TimeSpan start = end - Properties.Settings.Default.PressClipLength; if (start < TimeSpan.Zero) { start = TimeSpan.Zero; } if (end < TimeSpan.Zero) { end = TimeSpan.Zero; } Press p = new Press(start, end, u); presses.Add(p); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public bool IsPanopticonProcessingComplete() { try { return panopticonProcessor.IsComplete; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public string GetPanopticonFilename() { try { return panopticonProcessor.Filename; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public string GetVideoFilename() { try { return camera.VideoFileName; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public PanopticonInfo GetPanopticonInfo() { try { return panopticonProcessor.Info; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public List<Press> GetPresses() { try { return presses; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public TimeSpan GetStudyLength() { try { return camera.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void MakeAnnotation(Annotation a) { try { Tabletop.AddAnnotation(a); } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void SetResearchQuestion(string s) { try { if (!researchQuestionSet) { researchQuestionSet = true; Dispatcher.BeginInvoke(new Action(() => { Tabletop.SetResearchQuestion(s); })); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public long GetPanopticonSize() { try { string path = FileLocationUtility.GetPathInVideoFolderLocation(panopticonProcessor.Filename); FileInfo info = new FileInfo(path); return info.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public long GetVideoSize() { try { string path = FileLocationUtility.GetPathInVideoFolderLocation(camera.VideoFileName); FileInfo info = new FileInfo(path); return info.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public DateTime GetTime() { try { return DateTime.UtcNow; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } #endregion } }
{ "task_name": "lcc" }
Passage 1: Charles Oliver Fairbank (doctor) 12 Major Charles (Chas) Oliver Fairbank (RMC 1876), M.D. was born July 21, 1858 in Niagara Falls, Welland County Ontario. He was the son of famous Petrolia oil pioneer, James Henry Fairbank and grew up in the oil rush of Oil Springs and Petrolia. From the age of four to eight lived with his father in the Oil Springs log shanty. He was an oil operator who took the reins of all the family businesses in 1912 as the oil fields began declining. The businesses included oil production and a hardware store. The Fairbank family founded Fairbank Oil (still in operation) in 1861. He studied at Helmuth College in London, Ontario. Gentleman Cadet Fairbank was a member of the first class at Royal Military College of Canada, soon known as the "Old Eighteen." He entered 1st term on the 1st June 1876 and graduated in 1880. He graduated in 1891 with a degree of Doctor of Medicine from College of the Province of New York Known as King's College, now Columbia College. Due to his short stature, he was known as the little doctor. As part of the HQ staff, During World War I, he served as M.D. #1. The businesses included one of Canada’s last private banks, which was in continuous operation from 1869 - 1924 when it closed its doors voluntarily. He was the oil man who hit Canada's first gas gusher in 1914 and developed oil fields both in Bothwell, Ontario and in Elk Hills, California. Passage 2: Wesley Englehorn Wesley Theodore "Moose" Englehorn (January 21, 1890 – September 3, 1993) was an American football player and coach. Born in Helena, Montana, Englehorn first gained fame as a football player for Spokane High School. While he was a junior in high school, he was reportedly recruited by Princeton University to come east to play football for the school. A newspaper account in 1907 reported: "It is expected that Wesley Englehorn, the giant left tackle of the high school team, will also enter the Eastern college. If this materializes the Spokane high school will be weakened next year by the loss of two of its greatest players. ... Englehorn is also a strong basket ball player and track athlete." Englehorn did not enroll at Princeton and instead played for two years on the All Star Pacific Northwest football and basketball teams. He began his collegiate career at Washington State College. After playing one year of football at Washington State, Englehorn enrolled at Dartmouth College, where he played two years at the tackle position. He was elected team captain for the 1913 season, but he was declared ineligible under "the so-called three-year rule" because of his year at Washington State. Though ineligible to play, Englehorn served as the team's assistant coach in 1913 and was elected class president. He was selected as a first-team All-American in 1912. He graduated from Dartmouth in 1914 and worked as a football coach for several years thereafter. From 1914 to 1916, he was the football coach at Case School of Applied Science in Cleveland, Ohio. In 1917, he was hired as the line coach and first assistant football coach at Colgate University. In 1920, he was an assistant coach under Frank Cavanaugh at Boston College. In 1921, he was hired as the head football coach at Amherst College. In January 1922, Englehorn announced his retirement from coaching. Shortly before his death at age 103, Englehorn said, "It's the football I remember best ... the teammates .. the teamwork." Prior to his death in 1993, he was living at Stapeley Hall, a home for the elderly in the Germantown section of Philadelphia, Pennsylvania, and was the oldest living All-American football player. Passage 3: George Swinnock George Swinnock (1627–1673), nonconformist divine, born at Maidstone in Kent in 1627, was son of George Swinnock of Maidstone, whose father was mayor of the borough. Owing to the death of his father, George Swinnock, jun., was brought up in the house of his uncle Robert, a zealous puritan. He was educated at Emmanuel College, Cambridge, whence he removed on 7 October 1645 to Jesus College (Addit. MS. 5820, f. 162); he graduated B.A. in 1647–8, and then proceeded to Oxford to obtain preferment, entering as a commoner at Magdalen Hall. On 19 January 1648–9 he became chaplain at New College, and on 6 October following he was made a fellow of Balliol College by the parliamentary visitors. He was incorporated B.A. on 29 November 1650, and graduated M.A. on the next day. In the same year he resigned his fellowship, and was appointed vicar of Rickmansworth in Hertfordshire. In 1655 he was appointed to St. Leonard's chapel at Aston Clinton in Buckinghamshire, and on 10 January 1661 was presented to the vicarage of Great Kimble in the same county by Richard Hampden, to whom he was then chaplain. In the following year he was ejected for nonconformity, both from St. Leonard's and from Great Kimble, and took up his abode with the Hampden family at Great Hampden. Upon the issue of the Declaration of Indulgence in 1672 he retired to Maidstone, where he became pastor to a large congregation. He died on 10 November 1673, and was buried in the parish church. Passage 4: Paul Podmajersky Paul E. Podmajersky Jr. (November 17, 1916 – October 12, 1993) was an American football player. A native of Chicago, he played college football for Michigan State College (later known as Michigan State University), the University of Illinois, the University of Iowa, and the University of Wyoming. His wife later said that he transferred each year because "he kept getting better scholarship offers." He also played professional football in the National Football League as a guard for the Chicago Bears, appearing in one game during his rookie year of 1944. In 1945, Bears coach George Halas wrote Podmajersky a check for $1,000 to help him attend medical school. He graduated from the University of Colorado Medical School in 1948 and practiced medicine in Chicago for more than 30 years. His patients included the Halas family. He later moved to Oregon where he died in 1993 at age 76. Passage 5: Hsiao Bi-khim Hsiao Bi-khim (; born August 7, 1971) is a Taiwanese politician and member of the Legislative Yuan. Born in Kobe, Japan, Hsiao grew up in Tainan, Taiwan before moving to the United States. She graduated from Oberlin College in 1993 and Columbia University in 1995. Passage 6: Chanel College (Gladstone) Chanel College is a Catholic co-educational college in Gladstone, Queensland, Australia. Founded in 1966 by the Sisters of Mercy, the school was originally located at Star of the Sea Catholic Primary School, but it soon moved to 11 Paterson Street as Stella Maris College. The girls were educated at Stella Maris College and the boys at Chanel College, commenced by the Marist Brothers in 1968. Sister Bernadette continued to head Stella Maris and was resident principal of the girls' school, while Brother Austin Tanzer was the principal of Chanel. It wasn't until a later date, around 1976, that Stella Maris/Chanel College became a fully co-educational school with Brother John as Principal. At this time, it only educated students to Year 10; the year of completion of the Junior Certificate. Students then went on to attend the Gladstone State High School to complete Senior studies. After Brother John left the School, Brother Colin Marstin became Principal around 1978, and together with Brother Gonzaga, and Brother Joachim continued the efforts of the Marist Brother teachings. At this time the school became known as the Gladstone Catholic High School. It was the first Private Secondary school opened to serve Gladstone's youth, it still achieves its purpose . The first year 11 (Senior) class commenced in January 1982 and in November 1983, the very first year 12 class from the Gladstone Catholic High School graduated. Passage 7: Oberlin College Oberlin College is a private liberal arts college in Oberlin, Ohio. The college was founded as the Oberlin Collegiate Institute in 1833 by John Jay Shipherd and Philo Stewart. It is the oldest coeducational liberal arts college in the United States and the second oldest continuously operating coeducational institute of higher learning in the world. The Oberlin Conservatory of Music, part of the college, is the oldest continuously operating conservatory in the United States. Passage 8: William Merrill Whitman William Merrill Whitman (January 7, 1911 – November 24, 1993) was born in Omaha, Nebraska and graduated from the Nebraska State Teachers College in Wayne, Nebraska in 1930 with an A.B. degree. From 1930 to 1932, Whitman was a history teacher at Chadron High School in Nebraska. In 1932, Whitman attended the Northwestern University School of Law in Chicago, Illinois. He graduated cum laude from the University of Nebraska's College of Law with an L.L.B. degree in 1935. He was admitted to the Nebraska bar that same year. Passage 9: Jim Dennison James L. Dennison (born February 5, 1938) is a former American football and baseball coach, player, and college athletics administrator. On November 11, 2012, Dennison retired as the head football coach at Walsh University in North Canton, Ohio. He had held that position since February 11, 1994, the year before the school's football team began play in 1995. From 1973 to 1985, Dennison was the head football coach at the University of Akron. He was also the head baseball coach at Akron in 1966. Dennison served as the athletic director at Akron (1986–1993) and Walsh (1993–2007). He played college football and college baseball at the College of Wooster, from which he graduated in 1960. Passage 10: Jason Hsiao Jason Hsiao is the president and co-founder of Animoto, an online video creation service, and a former television producer. Hsiao graduated from Dartmouth College. Question: In which year was this college, from which Hsiao Bi-khim graduated in 1993, founded? Answer: 1833
{ "task_name": "hotpotqa" }
Passage 1: Raleigh, North Carolina Raleigh receives an average of 6.0 inches (15.2 cm) of snow in winter. Freezing rain and sleet also occur most winters, and occasionally the area experiences a major damaging ice storm. On January 24–25, 2000, Raleigh received its greatest snowfall from a single storm – 20.3 inches (52 cm) – the Winter Storm of January 2000. Storms of this magnitude are generally the result of cold air damming that affects the city due to its proximity to the Appalachian Mountains. Winter storms have caused traffic problems in the past as well. Passage 2: Winter In the UK, meteorologists consider winter to be the three coldest months of December, January and February. In Scandinavia, winter in one tradition begins on 14 October and ends on the last day of February. In Russia, currently calendar winter starts on 1 December and lasts through to the end of February, though traditionally it was reckoned from the Christmas (25 December in Julian calendar, or 7 January in Gregorian) until the Annunciation (25 March in Julian). In many countries in the Southern Hemisphere, including Australia, New Zealand and South Africa, winter begins on 1 June and ends on 31 August. In Celtic nations such as Ireland (using the Irish calendar) and in Scandinavia, the winter solstice is traditionally considered as midwinter, with the winter season beginning 1 November, on All Hallows, or Samhain. Winter ends and spring begins on Imbolc, or Candlemas, which is 1 or 2 February. This system of seasons is based on the length of days exclusively. (The three - month period of the shortest days and weakest solar radiation occurs during November, December and January in the Northern Hemisphere and May, June and July in the Southern Hemisphere.) Passage 3: Philadelphia The January daily average is 33.0 °F (0.6 °C), though, in a normal winter, the temperature frequently rises to 50 °F (10 °C) during thaws and dips to 10 °F (−12 °C) for 2 or 3 nights. July averages 78.1 °F (25.6 °C), although heat waves accompanied by high humidity and heat indices are frequent; highs reach or exceed 90 °F (32 °C) on 27 days of the year. The average window for freezing temperatures is November 6 thru April 2, allowing a growing season of 217 days. Early fall and late winter are generally dry; February's average of 2.64 inches (67 mm) makes it the area's driest month. The dewpoint in the summer averages between 59.1 °F (15 °C) to 64.5 °F (18 °C). Passage 4: Cranberry A common misconception about cranberry production is that the beds remain flooded throughout the year. During the growing season cranberry beds are not flooded, but are irrigated regularly to maintain soil moisture. Beds are flooded in the autumn to facilitate harvest and again during the winter to protect against low temperatures. In cold climates like Wisconsin, New England, and eastern Canada, the winter flood typically freezes into ice, while in warmer climates the water remains liquid. When ice forms on the beds, trucks can be driven onto the ice to spread a thin layer of sand that helps to control pests and rejuvenate the vines. Sanding is done every three to five years. Passage 5: Carnival During the celebration, theaters called tablados are built in many places throughout the cities, especially in Montevideo. Traditionally formed by men and now starting to be open to women, the different Carnival groups (Murgas, Lubolos or Parodistas) perform a kind of popular opera at the tablados, singing and dancing songs that generally relate to the social and political situation. The 'Calls' groups, basically formed by drummers playing the tamboril, perform candombe rhythmic figures. Revelers wear their festival clothing. Each group has its own theme. Women wearing elegant, bright dresses are called vedettes and provide a sensual touch to parades. Passage 6: Pearl Jam Pearl Jam is an American rock band formed in 1990 in Seattle, Washington. The band's current lineup comprises founding members Eddie Vedder (lead vocals), Mike McCready (lead guitar), Stone Gossard (rhythm guitar) and Jeff Ament (bass), and longtime drummer Matt Cameron. Keyboardist Boom Gaspar has also been a session/touring member with the band since 2002. Drummers Jack Irons, Dave Krusen, Matt Chamberlain and Dave Abbruzzese are former members of the band. Passage 7: Mount Zaō One striking feature of Zaō's famous ski resorts is the that appear in mid-winter. Strong wind over the nearby lake fling water droplets which freeze against the trees and their branches, until near-horizontal icicles begin to form. Falling snow settles on the ice formations, and the end result is a grotesque figure of a tree. The effect of a full forest of such trees gives visitors a ghostly impression. Zaō is one of the 100 famous mountains in Japan. Passage 8: Snow in Florida January 2 -- 3, 2018: A winter storm resulted in snow and a wintry mix (freezing rain, sleet, and ice) across northern Florida from Tallahassee to the outskirts of Jacksonville and as far south as Gainesville, with temperatures in the 20s and dewpoints in the teens in the morning. A winter storm warning was in effect on the morning of January 3 for Nassau, Baker, Union, Columbia, Gilchrist, Suwanee, Hamilton, Lafayette, Madison, Taylor, Jefferson, and Leon Counties, prompting several school districts to cancel classes on January 3. Tallahassee received 0.10 - 0.20 in of snow, which was the first measurable snowfall in the city since December 1989 (it sees flurries every few years). The Tallahassee snowfall followed a couple hours of freezing rain. The Florida Highway Patrol closed Interstate 10 from Tallahassee to Madison for most of the morning of January 3 as well as several bridges in North - Central Florida that had accumulated a dangerous amount of ice. Recorded ice accumulations included 0.25 in in Hilliard and Lake City and 0.10 in in Perry. Passage 9: Paris Spring and autumn have, on average, mild days and fresh nights but are changing and unstable. Surprisingly warm or cool weather occurs frequently in both seasons. In winter, sunshine is scarce; days are cold but generally above freezing with temperatures around 7 °C (45 °F). Light night frosts are however quite common, but the temperature will dip below −5 °C (23 °F) for only a few days a year. Snow falls every year, but rarely stays on the ground. The city sometimes sees light snow or flurries with or without accumulation. Passage 10: Northern Hemisphere The Arctic is the region north of the Arctic Circle. Its climate is characterized by cold winters and cool summers. Precipitation mostly comes in the form of snow. The Arctic experiences some days in summer when the Sun never sets, and some days during the winter when it never rises. The duration of these phases varies from one day for locations right on the Arctic Circle to several months near the North Pole, which is the middle of the Northern Hemisphere. Passage 11: Crimean War Notable documentation of the war was provided by William Howard Russell (writing for The Times newspaper) and the photographs of Roger Fenton.:306–309 News from war correspondents reached all nations involved in the war and kept the public citizenry of those nations better informed of the day-to-day events of the war than had been the case in any other war to that date. The British public was very well informed regarding the day-to-day realities of the war in the Crimea. After the French extended the telegraph to the coast of the Black Sea during the winter of 1854, the news reached London in two days. When the British laid an underwater cable to the Crimean peninsula in April 1855, news reached London in a few hours. The daily news reports energised public opinion, which brought down the Aberdeen government and carried Lord Palmerston into office as prime minister.:304–11 Passage 12: In Hiding "In Hiding" is a song by the American rock band Pearl Jam. Featuring lyrics written by vocalist Eddie Vedder and music written by guitarist Stone Gossard, "In Hiding" is the eleventh track on the band's fifth studio album, "Yield" (1998). Despite the lack of a commercial single release, the song managed to reach number 13 on the "Billboard" Modern Rock Tracks chart and number 14 on their Mainstream Rock Tracks chart. Passage 13: North Carolina The climate of the coastal plain is influenced by the Atlantic Ocean, which keeps conditions mild in winter and moderate, although humid, in summer. The highest coastal, daytime temperature averages less than 89 °F (32 °C) during summer months. The coast has mild temperatures in winter, with daytime highs rarely below 40 °F (4 °C). The average daytime temperature in the coastal plain is usually in the mid-50s °F (11–14 °C) in winter. Temperatures in the coastal plain only occasionally drop below the freezing point at night. The coastal plain averages only around 1 inch (2.5 cm) of snow or ice annually, and in many years, there may be no snow or ice at all. Passage 14: Airdevronsix Icefalls Airdevronsix Icefalls () is a line of icefalls at the head of Wright Upper Glacier, in Victoria Land, Antarctica. Named by U.S. Navy Operation Deepfreeze (1956–57) for "U.S. Navy Air Development Squadron Six", which had been formed to provide air support for the Deep Freeze operations and which had also carried out many important Antarctic exploratory flights. Passage 15: Oklahoma City The average temperature is 61.4 °F (16.3 °C), with the monthly daily average ranging from 39.2 °F (4.0 °C) in January to 83.0 °F (28.3 °C) in July. Extremes range from −17 °F (−27 °C) on February 12, 1899 to 113 °F (45 °C) on August 11, 1936 and August 3, 2012; the last sub-zero (°F) reading was −5 °F (−21 °C) on February 10, 2011. Temperatures reach 100 °F (38 °C) on 10.4 days of the year, 90 °F (32 °C) on nearly 70 days, and fail to rise above freezing on 8.3 days. The city receives about 35.9 inches (91.2 cm) of precipitation annually, of which 8.6 inches (21.8 cm) is snow. Passage 16: Detroit Detroit and the rest of southeastern Michigan have a humid continental climate (Köppen Dfa) which is influenced by the Great Lakes; the city and close-in suburbs are part of USDA Hardiness zone 6b, with farther-out northern and western suburbs generally falling in zone 6a. Winters are cold, with moderate snowfall and temperatures not rising above freezing on an average 44 days annually, while dropping to or below 0 °F (−18 °C) on an average 4.4 days a year; summers are warm to hot with temperatures exceeding 90 °F (32 °C) on 12 days. The warm season runs from May to September. The monthly daily mean temperature ranges from 25.6 °F (−3.6 °C) in January to 73.6 °F (23.1 °C) in July. Official temperature extremes range from 105 °F (41 °C) on July 24, 1934 down to −21 °F (−29 °C) on January 21, 1984; the record low maximum is −4 °F (−20 °C) on January 19, 1994, while, conversely the record high minimum is 80 °F (27 °C) on August 1, 2006, the most recent of five occurrences. A decade or two may pass between readings of 100 °F (38 °C) or higher, which last occurred July 17, 2012. The average window for freezing temperatures is October 20 thru April 22, allowing a growing season of 180 days. Passage 17: Mongol invasion of Kievan Rus' In mid-1238, Batu Khan devastated the Crimea and pacified Mordovia. In the winter of 1239, he sacked Chernigov and Pereyaslav. After many days of siege, the horde stormed Kiev in December 1240. Despite the resistance of Danylo of Halych, Batu Khan managed to take two of his principal cities, Halych and Volodymyr - Volynskyi. The Mongols then resolved to ``reach the ultimate sea '', where they could proceed no further, and invaded Hungary and Poland. Passage 18: North Carolina In winter, the Piedmont is colder than the coast, with temperatures usually averaging in the upper 40s–lower 50s °F (8–12 °C) during the day and often dropping below the freezing point at night. The region averages around 3–5 in (8–13 cm) of snowfall annually in the Charlotte area, and slightly more north toward the Virginia border. The Piedmont is especially notorious for sleet and freezing rain. Freezing rain can be heavy enough to snarl traffic and break down trees and power lines. Annual precipitation and humidity are lower in the Piedmont than in the mountains or the coast, but even at its lowest, the average is 40 in (1,020 mm) per year. Passage 19: Seattle Autumn, winter, and early spring are frequently characterized by rain. Winters are cool and wet with December, the coolest month, averaging 40.6 °F (4.8 °C), with 28 annual days with lows that reach the freezing mark, and 2.0 days where the temperature stays at or below freezing all day; the temperature rarely lowers to 20 °F (−7 °C). Summers are sunny, dry and warm, with August, the warmest month, averaging 66.1 °F (18.9 °C), and with temperatures reaching 90 °F (32 °C) on 3.1 days per year, although 2011 is the most recent year to not reach 90 °F. The hottest officially recorded temperature was 103 °F (39 °C) on July 29, 2009; the coldest recorded temperature was 0 °F (−18 °C) on January 31, 1950; the record cold daily maximum is 16 °F (−9 °C) on January 14, 1950, while, conversely, the record warm daily minimum is 71 °F (22 °C) the day the official record high was set. The average window for freezing temperatures is November 16 thru March 10, allowing a growing season of 250 days. Passage 20: Tucson, Arizona Winters in Tucson are mild relative to other parts of the United States. Daytime highs in the winter range between 64 and 75 °F (18 and 24 °C), with overnight lows between 30 and 44 °F (−1 and 7 °C). Tucson typically averages one hard freeze per winter season, with temperatures dipping to the mid or low-20s (−7 to −4 °C), but this is typically limited to only a very few nights. Although rare, snow has been known to fall in Tucson, usually a light dusting that melts within a day. The most recent snowfall was on February 20, 2013 when 2.0 inches of snow blanketed the city, the largest snowfall since 1987. Question: How many winter days reach freezing in the city where the band who performed In Hiding was formed? Answer: 28 annual days
{ "task_name": "MuSiQue" }
Document: Published on Sep 26, 2017 Using creativity to forge a better tomorrow, it is our values that make a #SUPERSTAR. Arvida Byström (@arvidabystrom) is an artist, photographer, model and cyber sensation. Known for her photography, which questions femininity and gender standards using so-called “girly” aesthetics. The #SUPERSTAR Bold Women's is in stores now. Find us online at: Instagram: http://instagram.com/adidasoriginals SoundCloud: https://soundcloud.com/adidasoriginals Facebook: http://facebook.com/adidasoriginals Twitter: http://twitter.com/adidasoriginals Tumblr: http://adidasoriginals.tumblr.com ||||| A Swedish model says she has received rape threats for posing in an advertisement with unshaved legs. Arvida Byström, who is also a photographer and digital artist, appears in a video and photograph promoting Adidas Originals’ Superstar range. Byström, who has described the norm for women to shave as “fucked”, has hairy legs in the images and says she has faced a vicious backlash as a result. She wrote on Instagram: “Me being such an abled, white, cis body with its only nonconforming feature being a lil leg hair. Literally I’ve been getting rape threats in my DM inbox. I can’t even begin to imagine what it’s like to not possess all these privileges and try to exist in the world. Sending love and try to remember that not everybody has the same experiences being a person.” Many people posted abusive comments under the video on YouTube. One said: “Is this what some woman have become? No thanks.” Another wrote: “Stop brushing your teeth and wiping your ass too fucking feminazi retarded”. But she has also received significant support, with many taking aim at those posting abuse. Among the positive comments were: “It is something absurd to say in 2017 but she is so brave to show natural legs, you go girl!” Another commenter wrote: “Thank you Adidas for showing a woman how she really is and what femininity really implies.” Byström, 26, is renowned for challenging perceptions of femininity. She regularly poses with her body hair on show and has also posted pictures showing her cellulite. She uses hot pink in a feminist context as a backdrop to pieces that double as modernist, online commentary. With her fellow digital artist Molly Soda, Byström curated Pics Or It Didn’t Happen, a book containing 270 images that were censored by Instagram. The photos were mainly of female nipples, vaginal secretions and body hair. In the Adidas video, Byström says: “I think femininity is usually created from our culture so I think everybody can do feminine things, can be feminine. I feel like in today’s society we are very scared of that.” Adidas described her as “an artist, photographer, model and cyber sensation, known for her photography, which questions femininity and gender standards using so-called ‘girly’ aesthetics”. Summary: – A Swedish model says she's faced an onslaught of online harassment after daring to pose for an Adidas advertising campaign with unshaved legs, the BBC reports. "Literally I've been getting rape threats in my DM inbox," 26-year-old Arvida Byström writes on Instagram. The ad for sneakers was posted Sept. 26 on YouTube. “Is this what some woman have become? No thanks," the Guardian quotes one of the nicer comments on the video as reading. Byström says she's getting harassed despite having "an abled, white, cis body with its only nonconforming feature being a lil leg hair." She adds: "I can't even begin to imagine what it's like to not posses all these privileges and try to exist in the world." It hasn't all been negative. “It is something absurd to say in 2017 but she is so brave to show natural legs, you go girl!” one commenter writes. And Adidas says it's honored to work with the model, who "questions femininity and gender standards using so-called 'girly' aesthetics." In the past, Byström has called the default of women shaving their bodies "f---ed." She's known for posing for photos displaying her body hair and cellulite and has published a book of 270 images censored by Instagram because they showed female body hair, nipples, vaginal secretions, and more.
{ "task_name": "multi_news" }
Passage 1: Midnight Sons The Midnight Sons is a fictional team of supernatural superheroes appearing in American comic books published by Marvel Comics. Including Hellstorm, Jennifer Kale, Morbius, Werewolf by Night, and Ghost Riders Danny Ketch and Johnny Blaze, the team first appeared in "Ghost Rider" (vol. 2) #28 (August 1992). From December 1993–August 1994, Marvel branded all stories involving the group with a distinct family imprint and cover treatment. Passage 2: Blackheart Blackheart is a fictional character appearing in American comic books published by Marvel Comics. The character is usually depicted as an adversary to the superhero Ghost Rider. Created by writer Ann Nocenti and artist John Romita, Jr., Blackheart first appeared in "Daredevil" #270 (September 1989). The character has also appeared in other media, such as the 2000 video game "Marvel vs Capcom 2", and in the 2007 film "Ghost Rider", in which he was portrayed by actor Wes Bentley. Passage 3: Vengeance (comics) Vengeance is a fictional American comic book character owned by Marvel Comics. He was initially introduced as an antagonist for the Ghost Rider. Lt. Michael Badilino was the first known person to be host, now the entity is attached to Deputy Kowalski. Passage 4: Ghost Rider (Johnny Blaze) Ghost Rider (Johnny Blaze) is a fictional character, a superhero appearing in American comic books published by Marvel Comics. He is the second Marvel character to use the name Ghost Rider, following the Western comics hero later known as the Phantom Rider, and preceding Daniel Ketch. The character's story begins when motorcycle stuntman, Johnny Blaze, becomes bound to the Spirit of Vengeance Zarathos after making a deal with Mephisto to spare his surrogate father. With his supernatural powers, Johnny seeks vengeance as the "Ghost Rider". Passage 5: Steel Vengeance Steel Vengeance (original name Sadae Tsumura) was a female cyborg in the Marvel Comics "Ghost Rider" series. Passage 6: Ghost Rider (Danny Ketch) Ghost Rider (Daniel "Danny" Ketch) is a fictional superhero appearing in American comic books published by Marvel Comics. He is the third Marvel character to don the identity of Ghost Rider, after Johnny Blaze, the first supernatural Ghost Rider, and the Western hero known as the Phantom Rider, who used the name in 1967. Passage 7: Ghost Rider: Spirit of Vengeance Ghost Rider: Spirit of Vengeance is a 2011 American superhero film based on the Marvel Comics antihero Ghost Rider. It is the sequel to the 2007 film "Ghost Rider" and stars Nicolas Cage as Johnny Blaze the Ghost Rider with supporting roles portrayed by Ciarán Hinds (replacing Peter Fonda), Violante Placido, Johnny Whitworth, Christopher Lambert, and Idris Elba. The film was directed by Mark Neveldine and Brian Taylor, from a screenplay written by David S. Goyer, Scott M. Gimple and Seth Hoffman. "Ghost Rider: Spirit of Vengeance" was released in theaters on February 17, 2012, in 3D and 2D. Passage 8: Ghost Rider: Road to Damnation Ghost Rider: Road to Damnation is a six issue comics miniseries starring the supernatural biker superhero Ghost Rider. It is written by Garth Ennis, illustrated by Clayton Crain, and was first published under the Marvel Knights imprint of Marvel Comics from 2005 to 2006. Although "Road to Damnation" was the title of the story, the title of the book was simply "Ghost Rider" when it was first published. When the miniseries was collected into a single edition in 2006, it was published under the name: "Ghost Rider: Road to Damnation". Passage 9: Ghost Rider (Robbie Reyes) Roberto "Robbie" Reyes is a fictional superhero appearing in American comic books published by Marvel Comics. He is the fifth Marvel character to use the name Ghost Rider, after Alejandra Jones, Danny Ketch, Johnny Blaze and Carter Slade (also known as Phantom Rider). Passage 10: Idris Elba Idris Akuna Elba {'1': ", '2': ", '3': ", '4': "} ( , born 6 September 1972) is an English actor, producer, musician, and DJ. He is known for playing the narcotrafficker Stringer Bell in the HBO series "The Wire", DCI John Luther on the BBC One series "Luther", and Nelson Mandela in the biographical film "" (2013). He has been nominated four times for a Golden Globe Award for Best Actor in a Miniseries or Television Film, winning one, and was nominated five times for a Primetime Emmy Award. Question: What English actor known for starring on The Wire appeared in Ghost Rider: Spirit of Vengeance Answer: Idris Elba
{ "task_name": "hotpotqa" }
Passage 1: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 2: Bill Smith (footballer, born 1897) William Thomas Smith( born 9 April 1897, date of death unknown) was an English professional footballer. Passage 3: Cecil Hepworth Cecil Milton Hepworth (19 March 1874 – 9 February 1953) was a British film director, producer and screenwriter. He was among the founders of the British film industry and continued making films into the 1920s at his Walton Studios. In 1923 his company Hepworth Pictures went into receivership. His works include "Alice in Wonderland" (1903), the first film adaptation of Lewis Carroll's children's book "Alice's Adventures in Wonderland". Passage 4: The Cobweb (1917 film) The Cobweb is a 1917 British silent thriller film directed by Cecil M. Hepworth and starring Henry Edwards, Alma Taylor and Stewart Rome. A millionaire mistakenly believes that he has murdered his Mexican wife. It is based on the play "The Cobweb" by Naunton Davies and Leon M. Lion. Passage 5: Theodred II (Bishop of Elmham) Theodred II was a medieval Bishop of Elmham. The date of Theodred's consecration unknown, but the date of his death was sometime between 995 and 997. Passage 6: Etan Boritzer Etan Boritzer( born 1950) is an American writer of children ’s literature who is best known for his book" What is God?" first published in 1989. His best selling" What is?" illustrated children's book series on character education and difficult subjects for children is a popular teaching guide for parents, teachers and child- life professionals. Boritzer gained national critical acclaim after" What is God?" was published in 1989 although the book has caused controversy from religious fundamentalists for its universalist views. The other current books in the" What is?" series include What is Love?, What is Death?, What is Beautiful?, What is Funny?, What is Right?, What is Peace?, What is Money?, What is Dreaming?, What is a Friend?, What is True?, What is a Family?, What is a Feeling?" The series is now also translated into 15 languages. Boritzer was first published in 1963 at the age of 13 when he wrote an essay in his English class at Wade Junior High School in the Bronx, New York on the assassination of John F. Kennedy. His essay was included in a special anthology by New York City public school children compiled and published by the New York City Department of Education. Boritzer now lives in Venice, California and maintains his publishing office there also. He has helped numerous other authors to get published through" How to Get Your Book Published!" programs. Boritzer is also a yoga teacher who teaches regular classes locally and guest- teaches nationally. He is also recognized nationally as an erudite speaker on" The Teachings of the Buddha." Passage 7: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 8: Harry Wainwright (footballer) Harry Wainwright( born 1899; date of death unknown) was an English footballer. Passage 9: Thomas Scott (diver) Thomas Scott( 1907- date of death unknown) was an English diver. Passage 10: Albert Thompson (footballer, born 1912) Albert Thompson( born 1912, date of death unknown) was a Welsh footballer. Question: What is the date of death of the director of film The Cobweb (1917 Film)? Answer: 9 February 1953
{ "task_name": "2WikiMultihopQA" }
Passage 1: Per Fuglum Per Fuglum (7 January 1924 – 13 June 2008) was a Norwegian historian, born in Oslo. He was appointed professor at the University of Trondheim in 1973. Among his works are biographies of the Norwegian prime ministers Ole Richter (from 1964) and Gunnar Knudsen (from 1989). He has also written books on the history of temperance in Norway. Passage 2: Tracey Stern Tracey Stern is an American television writer and producer. Stern made her television debut writing for the first two seasons of" ER". She has also worked as a writer on" Pacific BlueSports NightAngelLeap YearsTouching EvilDesperate Housewives The Book of Daniel", and" Angela's Eyes". Stern has also worked as a producer for" Sports NightAngelDesperate Housewives" and" Angela's Eyes". The first season of" Desperate Housewives" was nominated for an Emmy award for Outstanding Drama Series at the 2005 awards. The producers shared the nomination for their work on the season. Passage 3: Jessie Rindom Jessie Rindom (4 October 1903 – 8 January 1981) was a Danish film actress. She appeared in 30 films between 1925 and 1980. Born in Rostock, Germany, she was the daughter of Danish actors Ellen Diedrich and Svend Rindom. She died in Copenhagen, Denmark. Passage 4: Leonard Martino Leonard L. Martino is a former Democratic member of the Pennsylvania House of Representatives. He was born in Butler to Michael and Angela Pitullio Martino. Passage 5: Jessie Rindom Jessie Rindom (4 October 1903 – 8 January 1981) was a Danish film actress. She appeared in 30 films between 1925 and 1980. Born in Rostock, Germany, she was the daughter of Danish actors Ellen Diedrich and Svend Rindom. She died in Copenhagen, Denmark. Passage 6: Angela Richter Angela Richter( born 1970 in Ravensburg) is a German- Croatian theatre director and author. Passage 7: Godwin Davy Godwin Davy( born 15 December 1979) is an Anguillan international footballer who plays as a goalkeeper. He made his international debut in a World Cup qualifying match against El Salvador, resulting in a lopsided match, losing 12- 0 in February 2008, and also played in the 4 – 0 loss to the same country in the return match in March 2008. Passage 8: Per Fuglum Per Fuglum (7 January 1924 – 13 June 2008) was a Norwegian historian, born in Oslo. He was appointed professor at the University of Trondheim in 1973. Among his works are biographies of the Norwegian prime ministers Ole Richter (from 1964) and Gunnar Knudsen (from 1989). He has also written books on the history of temperance in Norway. Passage 9: Willem Brakman Willem Pieter Jacobus Brakman( 1922 – 2008) was a Dutch writer who made his literary debut with the novel" Een winterreis" in 1961. Brakman received the P. C. Hooft Award in 1980. He was born on June 13th, 1922 in The Hague, Netherlands, and died on May 8th, 2008 in the same country. Passage 10: Svend Rindom Svend Rindom( 30 June 1884 – 11 December 1960) was a Danish screenwriter and film actor. He wrote for 36 films between 1911 and 1950 and appeared in approximately twelve films from 1912 to 1943. He was born in Copenhagen and died in Copenhagen. His wife was actress Ellen Diedrich and his daughter was actress Jessie Rindom. He is buried in the Assistens Cemetery in Copenhagen. Question: Are Svend Rindom and Angela Richter from the same country? Answer: no
{ "task_name": "2WikiMultihopQA" }
Russia had previously obtained recognition from the Ottoman Empire of the Tsar's role as special guardian of the Orthodox Christians in Moldavia and Wallachia. Now Russia used the Sultan's failure to resolve the issue of the protection of the Christian sites in the Holy Land as a pretext for Russian occupation of these Danubian provinces. Nicholas believed that the European powers, especially Austria, would not object strongly to the annexation of a few neighbouring Ottoman provinces, especially considering that Russia had assisted Austria's efforts in suppressing the Hungarian Revolution in 1849. Question: Who was given the special role of guardian over the Orthodox Christians in Moldavia and Wallachia? Answer: Russia Question: Who recognized and gave Russia the special guardian role? Answer: Ottoman Empire of the Tsar's Question: Who felt Europe would not object to the joining of neighboring Ottoman provinces? Answer: Nicholas
{ "task_name": "squadv2" }
package de.micromata.opengis.kml.v_2_2_0; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import de.micromata.opengis.kml.v_2_2_0.annotations.Obvious; import de.micromata.opengis.kml.v_2_2_0.atom.Author; import de.micromata.opengis.kml.v_2_2_0.xal.AddressDetails; /** * <Overlay> * <p> * This is an abstract element and cannot be used directly in a KML file. <Overlay> * is the base type for image overlays drawn on the planet surface or on the screen. * <Icon> specifies the image to use and can be configured to reload images based on * a timer or by camera changes. This element also includes specifications for stacking * order of multiple overlays and for adding color and transparency values to the base * image. * </p> * * Syntax: * <pre>&lt;!-- abstract element; do not create --&gt; * <strong>&lt;!-- <em>Overlay</em> id="ID" --&gt;</strong> &lt;!-- GroundOverlay,ScreenOverlay --&gt; * &lt;!-- inherited from <em>Feature</em> element --&gt; * &lt;name&gt;<em>...</em>&lt;/name&gt; &lt;!-- string --&gt; * &lt;visibility&gt;1&lt;/visibility&gt; &lt;!-- boolean --&gt; * &lt;open&gt;0&lt;/open&gt; &lt;!-- boolean --&gt; * <span>&lt;atom:author&gt;...&lt;atom:author&gt; &lt;!-- xmlns:atom --&gt; * &lt;atom:link&gt;...&lt;/atom:link&gt;</span><span> &lt;!-- xmlns:atom --&gt;</span> * &lt;address&gt;<em>...</em>&lt;/address&gt; &lt;!-- string --&gt; * &lt;xal:AddressDetails&gt;...&lt;/xal:AddressDetails&gt; &lt;!-- xmlns:xal --&gt;<br> &lt;phoneNumber&gt;...&lt;/phoneNumber&gt; &lt;!-- string --&gt;<br> &lt;Snippet maxLines="2"&gt;<em>...</em>&lt;/Snippet&gt; &lt;!-- string --&gt; * &lt;description&gt;<em>...</em>&lt;/description&gt; &lt;!-- string --&gt; * <span><em>&lt;AbstractView&gt;...&lt;/AbstractView&gt;</em> &lt;!-- Camera <em>or</em> LookAt --&gt;</span> * &lt;<em>TimePrimitive</em>&gt;...&lt;/<em>TimePrimitive</em>&gt; * &lt;styleUrl&gt;<em>...</em>&lt;/styleUrl&gt; &lt;!-- anyURI --&gt; * &lt;<em>StyleSelector&gt;...&lt;/StyleSelector&gt;</em> * &lt;Region&gt;...&lt;/Region&gt; * <span>&lt;Metadata&gt;...&lt;/Metadata&gt; &lt;!-- deprecated in KML 2.2 --&gt; * &lt;ExtendedData&gt;...&lt;/ExtendedData&gt; &lt;!-- new in KML 2.2 --&gt;</span> * * &lt;!-- specific to <em>Overlay</em> --&gt; * &lt;color&gt;ffffffff&lt;/color&gt; &lt;!-- kml:color --&gt; * &lt;drawOrder&gt;0&lt;/drawOrder&gt; &lt;!-- int --&gt; * &lt;Icon&gt; * &lt;href&gt;...&lt;/href&gt; * &lt;/Icon&gt; * <strong>&lt;!-- /<em>Overlay --</em>&gt;</strong></pre> * * Extends: * @see: <Feature> * * Extended By: * @see: <GroundOverlay> * @see: <PhotoOverlay * @see: <ScreenOverlay> * @see: Syntax * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AbstractOverlayType", propOrder = { "color", "drawOrder", "icon", "overlaySimpleExtension", "overlayObjectExtension" }) @XmlSeeAlso({ ScreenOverlay.class, PhotoOverlay.class, GroundOverlay.class }) public abstract class Overlay extends Feature implements Cloneable { /** * <color> * <p> * Color and opacity (alpha) values are expressed in hexadecimal notation. The range * of values for any one color is 0 to 255 (00 to ff). For alpha, 00 is fully transparent * and ff is fully opaque. The order of expression is aabbggrr, where aa=alpha (00 * to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). For example, * if you want to apply a blue color with 50 percent opacity to an overlay, you would * specify the following: <color>7fff0000</color>, where alpha=0x7f, blue=0xff, green=0x00, * and red=0x00. * </p> * <p> * Color values are expressed in hexadecimal notation, including opacity (alpha) values. * The order of expression is alpha, blue, green, red (aabbggrr). The range of values * for any one color is 0 to 255 (00 to ff). For opacity, 00 is fully transparent and * ff is fully opaque. For example, if you want to apply a blue color with 50 percent * opacity to an overlay, you would specify the following: <color>7fff0000</color> * </p> * <p> * Note: The <geomColor> element has been deprecated. Use <color> instead. * </p> * * * */ @XmlElement(defaultValue = "ffffffff") protected String color; /** * <draworder> * <p> * This element defines the stacking order for the images in overlapping overlays. * Overlays with higher <drawOrder> values are drawn on top of overlays with lower * <drawOrder> values. * </p> * * * */ @XmlElement(defaultValue = "0") protected int drawOrder; /** * <icon> see also <icon>. * <p> * <Icon> <href>Sunset.jpg</href> </Icon> * </p> * <p> * A custom Icon. In <IconStyle>, the only child element of <Icon> is <href>: <href>: * An HTTP address or a local file specification used to load an icon. * </p> * <p> * Defines an image associated with an Icon style or overlay. <Icon> has the same child * elements as <Link>. The required <href> child element defines the location of the * image to be used as the overlay or as the icon for the placemark. This location * can either be on a local file system or a remote web server. * </p> * <p> * Defines the image associated with the Overlay. The <href> element defines the location * of the image to be used as the Overlay. This location can be either on a local file * system or on a web server. If this element is omitted or contains no <href>, a rectangle * is drawn using the color and size defined by the ground or screen overlay. <Icon> * <href>icon.jpg</href> </Icon> * </p> * * Syntax: * <pre><strong>&lt;Icon id="ID"&gt;</strong> * &lt;!-- specific to Icon --&gt; * &lt;href&gt;<em>...</em>&lt;/href&gt; &lt;!-- anyURI --&gt; * &lt;refreshMode&gt;onChange&lt;/refreshMode&gt; * &lt;!-- kml:refreshModeEnum: onChange, onInterval, <em>or</em> onExpire --&gt; * &lt;refreshInterval&gt;4&lt;/refreshInterval&gt; &lt;!-- float --&gt; * &lt;viewRefreshMode&gt;never&lt;/viewRefreshMode&gt; * &lt;!-- kml:viewRefreshModeEnum: never, onStop, onRequest, onRegion --&gt; * &lt;viewRefreshTime&gt;4&lt;/viewRefreshTime&gt; &lt;!-- float --&gt; * &lt;viewBoundScale&gt;1&lt;/viewBoundScale&gt; &lt;!-- float --&gt; * &lt;viewFormat&gt;...&lt;/viewFormat&gt; &lt;!-- string --&gt; * &lt;httpQuery&gt;...&lt;/httpQuery&gt; &lt;!-- string --&gt; * <strong>&lt;/Icon&gt;</strong></pre> * * Contained By: * @see: <GroundOverlay> * @see: <IconStyle> * @see: <ScreenOverlay> * * * */ @XmlElement(name = "Icon") protected Icon icon; @XmlElement(name = "AbstractOverlaySimpleExtensionGroup") @XmlSchemaType(name = "anySimpleType") protected List<Object> overlaySimpleExtension; /** * <Object> * <p> * This is an abstract base class and cannot be used directly in a KML file. It provides * the id attribute, which allows unique identification of a KML element, and the targetId * attribute, which is used to reference objects that have already been loaded into * Google Earth. The id attribute must be assigned if the <Update> mechanism is to * be used. * </p> * * Syntax: * <pre>&lt;!-- abstract element; do not create --&gt;<strong> * &lt;!-- <em>Object</em> id="ID" targetId="NCName" --&gt; * &lt;!-- /<em>Object</em>&gt; --&gt;</strong></pre> * * * */ @XmlElement(name = "AbstractOverlayObjectExtensionGroup") protected List<AbstractObject> overlayObjectExtension; public Overlay() { super(); } /** * @see color * * @return * possible object is * {@link String} * */ public String getColor() { return color; } /** * @see color * * @param value * allowed object is * {@link String} * */ public void setColor(String value) { this.color = value; } /** * @see drawOrder * * @return * possible object is * {@link Integer} * */ public int getDrawOrder() { return drawOrder; } /** * @see drawOrder * * @param value * allowed object is * {@link Integer} * */ public void setDrawOrder(int value) { this.drawOrder = value; } /** * @see icon * * @return * possible object is * {@link de.micromata.opengis.kml.v_2_2_0.Link} * */ public Icon getIcon() { return icon; } /** * @see icon * * @param value * allowed object is * {@link de.micromata.opengis.kml.v_2_2_0.Link} * */ public void setIcon(Icon value) { this.icon = value; } /** * @see overlaySimpleExtension * */ public List<Object> getOverlaySimpleExtension() { if (overlaySimpleExtension == null) { overlaySimpleExtension = new ArrayList<Object>(); } return this.overlaySimpleExtension; } /** * @see overlayObjectExtension * */ public List<AbstractObject> getOverlayObjectExtension() { if (overlayObjectExtension == null) { overlayObjectExtension = new ArrayList<AbstractObject>(); } return this.overlayObjectExtension; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = ((prime*result)+((color == null)? 0 :color.hashCode())); result = ((prime*result)+ drawOrder); result = ((prime*result)+((icon == null)? 0 :icon.hashCode())); result = ((prime*result)+((overlaySimpleExtension == null)? 0 :overlaySimpleExtension.hashCode())); result = ((prime*result)+((overlayObjectExtension == null)? 0 :overlayObjectExtension.hashCode())); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (super.equals(obj) == false) { return false; } if ((obj instanceof Overlay) == false) { return false; } Overlay other = ((Overlay) obj); if (color == null) { if (other.color!= null) { return false; } } else { if (color.equals(other.color) == false) { return false; } } if (drawOrder!= other.drawOrder) { return false; } if (icon == null) { if (other.icon!= null) { return false; } } else { if (icon.equals(other.icon) == false) { return false; } } if (overlaySimpleExtension == null) { if (other.overlaySimpleExtension!= null) { return false; } } else { if (overlaySimpleExtension.equals(other.overlaySimpleExtension) == false) { return false; } } if (overlayObjectExtension == null) { if (other.overlayObjectExtension!= null) { return false; } } else { if (overlayObjectExtension.equals(other.overlayObjectExtension) == false) { return false; } } return true; } /** * Creates a new instance of {@link Icon} and set it to icon. * * This method is a short version for: * <code> * Icon icon = new Icon(); * this.setIcon(icon); </code> * * */ public Icon createAndSetIcon() { Icon newValue = new Icon(); this.setIcon(newValue); return newValue; } /** * @see overlaySimpleExtension * * @param overlaySimpleExtension */ public void setOverlaySimpleExtension(final List<Object> overlaySimpleExtension) { this.overlaySimpleExtension = overlaySimpleExtension; } /** * add a value to the overlaySimpleExtension property collection * * @param overlaySimpleExtension * Objects of the following type are allowed in the list: {@link Object} * @return * <tt>true</tt> (as general contract of <tt>Collection.add</tt>). */ public Overlay addToOverlaySimpleExtension(final Object overlaySimpleExtension) { this.getOverlaySimpleExtension().add(overlaySimpleExtension); return this; } /** * @see overlayObjectExtension * * @param overlayObjectExtension */ public void setOverlayObjectExtension(final List<AbstractObject> overlayObjectExtension) { this.overlayObjectExtension = overlayObjectExtension; } /** * add a value to the overlayObjectExtension property collection * * @param overlayObjectExtension * Objects of the following type are allowed in the list: {@link AbstractObject} * @return * <tt>true</tt> (as general contract of <tt>Collection.add</tt>). */ public Overlay addToOverlayObjectExtension(final AbstractObject overlayObjectExtension) { this.getOverlayObjectExtension().add(overlayObjectExtension); return this; } /** * @see objectSimpleExtension * */ @Obvious @Override public void setObjectSimpleExtension(final List<Object> objectSimpleExtension) { super.setObjectSimpleExtension(objectSimpleExtension); } @Obvious @Override public Overlay addToObjectSimpleExtension(final Object objectSimpleExtension) { super.getObjectSimpleExtension().add(objectSimpleExtension); return this; } /** * @see styleSelector * */ @Obvious @Override public void setStyleSelector(final List<StyleSelector> styleSelector) { super.setStyleSelector(styleSelector); } @Obvious @Override public Overlay addToStyleSelector(final StyleSelector styleSelector) { super.getStyleSelector().add(styleSelector); return this; } /** * @see featureSimpleExtension * */ @Obvious @Override public void setFeatureSimpleExtension(final List<Object> featureSimpleExtension) { super.setFeatureSimpleExtension(featureSimpleExtension); } @Obvious @Override public Overlay addToFeatureSimpleExtension(final Object featureSimpleExtension) { super.getFeatureSimpleExtension().add(featureSimpleExtension); return this; } /** * @see featureObjectExtension * */ @Obvious @Override public void setFeatureObjectExtension(final List<AbstractObject> featureObjectExtension) { super.setFeatureObjectExtension(featureObjectExtension); } @Obvious @Override public Overlay addToFeatureObjectExtension(final AbstractObject featureObjectExtension) { super.getFeatureObjectExtension().add(featureObjectExtension); return this; } /** * fluent setter * @see #setColor(String) * * @param color * required parameter */ public Overlay withColor(final String color) { this.setColor(color); return this; } /** * fluent setter * @see #setDrawOrder(int) * * @param drawOrder * required parameter */ public Overlay withDrawOrder(final int drawOrder) { this.setDrawOrder(drawOrder); return this; } /** * fluent setter * @see #setIcon(Icon) * * @param icon * required parameter */ public Overlay withIcon(final Icon icon) { this.setIcon(icon); return this; } /** * fluent setter * @see #setOverlaySimpleExtension(List<Object>) * * @param overlaySimpleExtension * required parameter */ public Overlay withOverlaySimpleExtension(final List<Object> overlaySimpleExtension) { this.setOverlaySimpleExtension(overlaySimpleExtension); return this; } /** * fluent setter * @see #setOverlayObjectExtension(List<AbstractObject>) * * @param overlayObjectExtension * required parameter */ public Overlay withOverlayObjectExtension(final List<AbstractObject> overlayObjectExtension) { this.setOverlayObjectExtension(overlayObjectExtension); return this; } @Obvious @Override public Overlay withObjectSimpleExtension(final List<Object> objectSimpleExtension) { super.withObjectSimpleExtension(objectSimpleExtension); return this; } @Obvious @Override public Overlay withId(final String id) { super.withId(id); return this; } @Obvious @Override public Overlay withTargetId(final String targetId) { super.withTargetId(targetId); return this; } @Obvious @Override public Overlay withName(final String name) { super.withName(name); return this; } @Obvious @Override public Overlay withVisibility(final Boolean visibility) { super.withVisibility(visibility); return this; } @Obvious @Override public Overlay withOpen(final Boolean open) { super.withOpen(open); return this; } @Obvious @Override public Overlay withAtomAuthor(final Author atomAuthor) { super.withAtomAuthor(atomAuthor); return this; } @Obvious @Override public Overlay withAtomLink(final de.micromata.opengis.kml.v_2_2_0.atom.Link atomLink) { super.withAtomLink(atomLink); return this; } @Obvious @Override public Overlay withAddress(final String address) { super.withAddress(address); return this; } @Obvious @Override public Overlay withXalAddressDetails(final AddressDetails xalAddressDetails) { super.withXalAddressDetails(xalAddressDetails); return this; } @Obvious @Override public Overlay withPhoneNumber(final String phoneNumber) { super.withPhoneNumber(phoneNumber); return this; } @Obvious @Override public Overlay withSnippet(final Snippet snippet) { super.withSnippet(snippet); return this; } @Obvious @Override public Overlay withSnippetd(final String snippetd) { super.withSnippetd(snippetd); return this; } @Obvious @Override public Overlay withDescription(final String description) { super.withDescription(description); return this; } @Obvious @Override public Overlay withAbstractView(final AbstractView abstractView) { super.withAbstractView(abstractView); return this; } @Obvious @Override public Overlay withTimePrimitive(final TimePrimitive timePrimitive) { super.withTimePrimitive(timePrimitive); return this; } @Obvious @Override public Overlay withStyleUrl(final String styleUrl) { super.withStyleUrl(styleUrl); return this; } @Obvious @Override public Overlay withStyleSelector(final List<StyleSelector> styleSelector) { super.withStyleSelector(styleSelector); return this; } @Obvious @Override public Overlay withRegion(final Region region) { super.withRegion(region); return this; } @Obvious @Override public Overlay withMetadata(final Metadata metadata) { super.withMetadata(metadata); return this; } @Obvious @Override public Overlay withExtendedData(final ExtendedData extendedData) { super.withExtendedData(extendedData); return this; } @Obvious @Override public Overlay withFeatureSimpleExtension(final List<Object> featureSimpleExtension) { super.withFeatureSimpleExtension(featureSimpleExtension); return this; } @Obvious @Override public Overlay withFeatureObjectExtension(final List<AbstractObject> featureObjectExtension) { super.withFeatureObjectExtension(featureObjectExtension); return this; } @Override public Overlay clone() { Overlay copy; copy = ((Overlay) super.clone()); copy.icon = ((icon == null)?null:((Icon) icon.clone())); copy.overlaySimpleExtension = new ArrayList<Object>((getOverlaySimpleExtension().size())); for (Object iter: overlaySimpleExtension) { copy.overlaySimpleExtension.add(iter); } copy.overlayObjectExtension = new ArrayList<AbstractObject>((getOverlayObjectExtension().size())); for (AbstractObject iter: overlayObjectExtension) { copy.overlayObjectExtension.add(iter.clone()); } return copy; } }
{ "task_name": "lcc" }
Passage 1: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 2: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 3: Brian Kennedy (gallery director) Brian Patrick Kennedy( born 5 November 1961) is an Irish- born art museum director who has worked in Ireland and Australia, and now lives and works in the United States. He is currently the director of the Peabody Essex Museum. He was the director of the Toledo Museum of Art in Ohio from 2010 to 2019. He was the director of the Hood Museum of Art from 2005 to 2010, and the National Gallery of Australia( Canberra) from 1997- 2004. Passage 4: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 5: Marco Foschi Marco Foschi( born April 1, 1977) is an Italian actor and voice actor. He played in the 2012 film" King of the Sands" directed by Najdat Anzour and in the 2012 American- Italian television movie" Barabbas", as Jesus. Passage 6: King of the Children King of the Children is a 1987 drama film directed by Chen Kaige and starring Chen Shaohua. The film was based on a novella of the same name by Ah Cheng. The film competed for the Palme D'Or at the 1988 Cannes Film Festival. Passage 7: Chen Kaige Chen Kaige (born 12 August 1952) is a Chinese film director and a leading figure of the fifth generation of Chinese cinema. His films are known for their visual flair and epic storytelling. Chen won the Palme d'Or at 1993 Cannes Film Festival and the International Federation of Film Critics (FIPRESCI) Award in 1993. Passage 8: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Passage 9: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 10: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Question: Which country the director of film King Of The Children is from? Answer: Chinese
{ "task_name": "2WikiMultihopQA" }
Passage 1: Chris Barns Chris 'Brolga' Barns is the founder of the Kangaroo Sanctuary in Alice Springs. He was featured in the 2013 BBC documentary series "Kangaroo Dundee". Barns and the Kangaroo Sanctuary came to international attention when Roger, one of the earlier kangaroos that he adopted, went viral for his muscular physique. Passage 2: Kristian Leontiou Kristian Leontiou (born February 1982) is a British singer of Greek Cypriot descent, and is the singer for the indie rock band One eskimO. Passage 3: Caspar Babypants Caspar Babypants is the stage name of children's music artist Chris Ballew, who is also widely known as the singer of The Presidents of the United States of America. Passage 4: Never Have to Be Alone Never Have to Be Alone is a song by American gospel singer CeCe Winans, released in 2017. The song earned the singer a Grammy Award for Best Gospel Performance/ Song. The song is from the artist's" Let Them Fall in Love" album. Passage 5: Les Paul Lester William Polsfuss (June 9, 1915 – August 12, 2009), known as Les Paul, was an American jazz, country, and blues guitarist, songwriter, luthier, and inventor. He was one of the pioneers of the solid-body electric guitar, and his techniques served as inspiration for the Gibson Les Paul. Paul taught himself how to play guitar, and while he is mainly known for jazz and popular music, he had an early career in country music. He is credited with many recording innovations. Although he was not the first to use the technique, his early experiments with overdubbing (also known as sound on sound), delay effects such as tape delay, phasing effects and multitrack recording were among the first to attract widespread attention. His innovative talents extended into his playing style, including licks, trills, chording sequences, fretting techniques and timing, which set him apart from his contemporaries and inspired many guitarists of the present day. He recorded with his wife, the singer and guitarist Mary Ford, in the 1950s, and they sold millions of records. Among his many honors, Paul is one of a handful of artists with a permanent, stand-alone exhibit in the Rock and Roll Hall of Fame. He is prominently named by the music museum on its website as an "architect" and a "key inductee" with Sam Phillips and Alan Freed. Les Paul is the only person to be included in both the Rock and Roll Hall of Fame and the National Inventors Hall of Fame. Passage 6: Billy Milano Billy Milano is a Bronx- born heavy metal musician now based in Austin, Texas. He is the singer and- occasionally- guitarist and bassist of crossover thrash band M.O.D., and he was also the singer of its predecessor, Stormtroopers of Death. He was also the singer of United Forces, which also featured his Stormtroopers of Death bandmate Dan Lilker. Passage 7: The Kangaroo (song) "The Kangaroo" is a 1953 instrumental written and recorded by Les Paul and released as a single. Passage 8: Bernie Bonvoisin Bernard Bonvoisin, known as Bernie Bonvoisin( born 9 July 1956 in Nanterre, Hauts- de- Seine), is a French hard rock singer and film director. He is best known for having been the singer of Trust. He was one of the best friends of Bon Scott the singer of AC/ DC and together they recorded the song" Ride On" which was one of the last songs by Bon Scott. Passage 9: O Valencia! " O Valencia!" is the fifth single by the indie rock band The Decemberists, and the first released from their fourth studio album," The Crane Wife". The music was written by The Decemberists and the lyrics by Colin Meloy. It tells a story of two star- crossed lovers. The singer falls in love with a person who belongs to an opposing gang. At the end of the song, the singer's lover jumps in to defend the singer, who is confronting his lover's brother( the singer's" sworn enemy") and is killed by the bullet intended for the singer. Passage 10: Ami Banglay Gaan Gai " Ami Banglay Gaan Gai" is a patriotic song by Bangladeshi poet and composer Pratul Mukhopadhyay. He is also the composer and original singer of the song. The song was nominated as one the most popular songs on March, 2006. Question: Which country the performer of song The Kangaroo (Song) is from? Answer: American
{ "task_name": "2WikiMultihopQA" }
Passage 1: Why Don't You Want My Love? " Why Do n't You Want My Love?" is a single by American singer La Toya Jackson. After recording her sixth studio album" Bad Girl", which would be distributed in 1991, Jackson signed a deal with BCM Records in Germany. The song was intended to be the lead single for a new album under the BCM label, but the company went bankrupt before the album could be completed. " Why Do n't You Want My Love?" was originally scheduled for a release in fall 1990 but was delayed several times until its release in January 1991. The single was released in Germany, Austria and Switzerland. BCM started a huge print campaign for the CD single, advertising the single with the caption" A fresh new start with BCM", and there is even a short message for all DJ s at the end of the CD single with Jackson's soft voice asking," Now DJs, why" do n't" you want my love?". The single was released on 7", 12" and CD formats, but failed to reach the charts. In 1993, the song was licensed to the German label" Legend", who released a remix of the song along with the 12 tracks from Jackson's" Bad Girl" album. The compilation was titled" Why Do n't You Want My Love?". Jackson quickly signed a new record deal with Pump Records in the Netherlands and released a new single and album only 10 months later. Passage 2: A House Without Love " A House Without Love" is a song composed by Hank Williams. It was released as the B-side to" Why Do n't You Love Me" in 1950 on MGM Records. Passage 3: Why Don't You Haul Off and Love Me " Why Do n't You Haul Off and Love Me" is a song first recorded by Wayne Raney, written by Raney and his musical partner Lonnie Glosson. Wayne Raney had the most successful release of his career when his version of" Why Do n't You Haul Off and Love Me" went to number one on the Country& Western charts. Passage 4: Don't Say You Love Me (Fifth Harmony song) " Do n't Say You Love Me" is a song recorded by American group Fifth Harmony for their self- titled third studio album( 2017). It was written by Nate Cyphert, Ian Kirkpatrick, Henrik Barman Michaelsen, Edvard Forre Erfjord, Lisa Scinta. A mid-tempo ballad," Do n't Say You Love Me" incorporates a tropical music production that runs through a moderate dembow rhythm, using a minimal instrumentation; it has an acoustic guitar riff and a syncopated drumline. Lyrically, it is a melancholic torch song that finds the group asking a" close but inconsistent" lover for an honest relationship. The lyrics are structured in verse – pre-chorus – chorus form. " Do n't Say You Love Me" was critically well- received by music critics who reviewed the song upon the album's release, with some citing it as one of the highlights of the record while praising the melancholy and vulnerability expressed in the song's lyrical content and sonic elements. An accompanying music video for" Do n't Say You Love Me" was released on May 18, 2018 as a farewell before the group went into an indefinite hiatus. Directed by P.R. Brown, the video was shot in an abandoned warehouse and features the four members dancing in gowns and long dresses while emotionally singing the song. At the end of the video, the group embrace while holding hands in a circle before leaving through a door in the room that remains open as the last member leaves. The song was performed for the first time live during their appearance on MTV's reboot of" Total Request Live" alongside" He Like That" on October 27, 2017. Fifth Harmony also sung" Do n't Say You Love Me" to a small group of fans at the Hollywood Boulevard street in Hollywood, California, in February 2018. It was also included on the setlist of their PSA Tour( 2017 – 18). Passage 5: Ramblin' Man (Hank Williams song) " Ramblin' Man" is a song written in 1951 by Hank Williams. It was released as the B-side to the 1953# 1 hit" Take These Chains from My Heart", as well as to the 1976 re-release of" Why Do n't You Love Me". It is also included on the" 40 Greatest Hits", a staple of his CD re-released material. Passage 6: Don't You Love Me (49ers song) ' Do n't You Love Me' is a 1990 dance single by 49ers. The single featured a vocal sample from Jody Watley's 1987 hit" Do n't You Want Me" On the European charts, it went# 12 in the UK,# 10 in Switzerland, and# 6 in Ireland. On the US charts, it was the group's second and last# 1 on the dance chart, where it spent two weeks at the top. " Do n't You Love Me" was the group's only entry on the Hot 100 peaking at# 78. Passage 7: Why Don't You Love Me (Hank Williams song) "Why Don't You Love Me" is a song by American singer and guitarist Hank Williams. The song reached number one on the U.S. Country & Western chart. It was released as a single in 1950 with the B-side "A House Without Love". Passage 8: Hank Williams Hiram "Hank" Williams (September 17, 1923 – January 1, 1953) was an American singer-songwriter and musician. Regarded as one of the most significant and influential American singers and songwriters of the 20th century, Williams recorded 35 singles (five released posthumously) that reached the Top 10 of the "Billboard" Country & Western Best Sellers chart, including 11 that ranked number one (three posthumously). Born in Mount Olive, Butler County, Alabama, Williams relocated to Georgiana with his family, where he met Rufus Payne, an African American blues musician, who gave him guitar lessons in exchange for meals or money. Payne had a major influence on Williams' later musical style, along with Roy Acuff and Ernest Tubb. Williams would later relocate to Montgomery, where he began his music career in 1937, when producers at radio station WSFA hired him to perform and host a 15-minute program. He formed the Drifting Cowboys backup band, which was managed by his mother, and dropped out of school to devote his time to his career. When several of his band members were conscripted into military service during World War II, Williams had trouble with their replacements, and WSFA terminated his contract because of his alcohol abuse. Williams eventually married Audrey Sheppard, who was his manager for nearly a decade. After recording "Never Again" and "Honky Tonkin'" with Sterling Records, he signed a contract with MGM Records. In 1947, he released "Move It on Over", which became a hit, and also joined the "Louisiana Hayride" radio program. One year later, he released a cover of "Lovesick Blues" recorded at Herzog Studio in Cincinnati, which carried him into the mainstream of music. After an initial rejection, Williams joined the Grand Ole Opry. He was unable to read or notate music to any significant degree. Among the hits he wrote were "Your Cheatin' HeartHey, Good Lookin'", and "I'm So Lonesome I Could Cry". Years of back pain, alcoholism and prescription drug abuse severely compromised his health. In 1952 he divorced Sheppard and was dismissed by the Grand Ole Opry because of his unreliability and alcohol abuse. On New Year's Day 1953, he died suddenly while traveling to a concert in Canton, Ohio, at the age of 29. Despite his short life, Williams is one of the most celebrated and influential popular musicians of the 20th century, especially in regard to country music. Many artists covered songs Williams wrote and recorded. He influenced Elvis Presley, Johnny Cash, Chuck Berry, Jerry Lee Lewis, Bob Dylan, George Jones, Charley Pride, and The Rolling Stones, among others. Williams was inducted into the Country Music Hall of Fame (1961), the Songwriters Hall of Fame (1970), and the Rock and Roll Hall of Fame (1987). The Pulitzer Prize jury in 2010 awarded him a posthumous special citation "for his craftsmanship as a songwriter who expressed universal feelings with poignant simplicity and played a pivotal role in transforming country music into a major musical and cultural force in American life." Passage 9: Sexy Dirty Love " Sexy Dirty Love" is a song recorded by American singer Demi Lovato for her sixth studio album," Tell Me You Love Me"( 2017). It was released on September 22, 2017, by Hollywood, Island and Safehouse Records as the third promotional single from the record, following" Tell Me You Love Me" and" You Do n't Do It for Me AnymoreSexy Dirty Love" is featured on the set list of Lovato's 2018 Tell Me You Love Me World Tour. Passage 10: Billy Milano Billy Milano is a Bronx- born heavy metal musician now based in Austin, Texas. He is the singer and- occasionally- guitarist and bassist of crossover thrash band M.O.D., and he was also the singer of its predecessor, Stormtroopers of Death. He was also the singer of United Forces, which also featured his Stormtroopers of Death bandmate Dan Lilker. Question: What is the date of death of the performer of song Why Don'T You Love Me (Hank Williams Song)? Answer: January 1, 1953
{ "task_name": "2WikiMultihopQA" }
/* * Copyright 2014 the original author or authors. * * 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. */ package org.springframework.social.connect.web; import java.util.Collections; import java.util.List; import javax.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.GenericTypeResolver; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionFactory; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.support.OAuth1ConnectionFactory; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.support.URIBuilder; import org.springframework.stereotype.Controller; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.view.RedirectView; /** * Spring MVC Controller for handling the provider user sign-in flow. * <ul> * <li>POST /signin/{providerId} - Initiate user sign-in with {providerId}.</li> * <li>GET /signin/{providerId}?oauth_token&amp;oauth_verifier||code - Receive {providerId} authentication callback and establish the connection.</li> * </ul> * @author Keith Donald */ @Controller @RequestMapping("/signin") public class ProviderSignInController implements InitializingBean { private final static Log logger = LogFactory.getLog(ProviderSignInController.class); private final ConnectionFactoryLocator connectionFactoryLocator; private final UsersConnectionRepository usersConnectionRepository; private final MultiValueMap<Class<?>, ProviderSignInInterceptor<?>> signInInterceptors = new LinkedMultiValueMap<Class<?>, ProviderSignInInterceptor<?>>(); private final SignInAdapter signInAdapter; private String applicationUrl; private String signInUrl = "/signin"; private String signUpUrl = "/signup"; private String postSignInUrl = "/"; private ConnectSupport connectSupport; private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); /** * Creates a new provider sign-in controller. * @param connectionFactoryLocator the locator of {@link ConnectionFactory connection factories} used to support provider sign-in. * Note: this reference should be a serializable proxy to a singleton-scoped target instance. * This is because {@link ProviderSignInAttempt} are session-scoped objects that hold ConnectionFactoryLocator references. * If these references cannot be serialized, NotSerializableExceptions can occur at runtime. * @param usersConnectionRepository the global store for service provider connections across all users. * Note: this reference should be a serializable proxy to a singleton-scoped target instance. * @param signInAdapter handles user sign-in */ @Inject public ProviderSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository, SignInAdapter signInAdapter) { this.connectionFactoryLocator = connectionFactoryLocator; this.usersConnectionRepository = usersConnectionRepository; this.signInAdapter = signInAdapter; } /** * Configure the list of sign in interceptors that should receive callbacks during the sign in process. * Convenient when an instance of this class is configured using a tool that supports JavaBeans-based configuration. * @param interceptors the sign in interceptors to add */ public void setSignInInterceptors(List<ProviderSignInInterceptor<?>> interceptors) { for (ProviderSignInInterceptor<?> interceptor : interceptors) { addSignInInterceptor(interceptor); } } /** * Sets the URL of the application's sign in page. * Defaults to "/signin". * @param signInUrl the signIn URL */ public void setSignInUrl(String signInUrl) { this.signInUrl = signInUrl; } /** * Sets the URL to redirect the user to if no local user account can be mapped when signing in using a provider. * Defaults to "/signup". * @param signUpUrl the signUp URL */ public void setSignUpUrl(String signUpUrl) { this.signUpUrl = signUpUrl; } /** * Sets the default URL to redirect the user to after signing in using a provider. * Defaults to "/". * @param postSignInUrl the postSignIn URL */ public void setPostSignInUrl(String postSignInUrl) { this.postSignInUrl = postSignInUrl; } /** * Configures the base secure URL for the application this controller is being used in e.g. <code>https://myapp.com</code>. Defaults to null. * If specified, will be used to generate OAuth callback URLs. * If not specified, OAuth callback URLs are generated from web request info. * You may wish to set this property if requests into your application flow through a proxy to your application server. * In this case, the request URI may contain a scheme, host, and/or port value that points to an internal server not appropriate for an external callback URL. * If you have this problem, you can set this property to the base external URL for your application and it will be used to construct the callback URL instead. * @param applicationUrl the application URL value */ public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } /** * Sets a strategy to use when persisting information that is to survive past the boundaries of a request. * The default strategy is to set the data as attributes in the HTTP Session. * @param sessionStrategy the session strategy. */ public void setSessionStrategy(SessionStrategy sessionStrategy) { this.sessionStrategy = sessionStrategy; } /** * Adds a ConnectInterceptor to receive callbacks during the connection process. * Useful for programmatic configuration. * @param interceptor the connect interceptor to add */ public void addSignInInterceptor(ProviderSignInInterceptor<?> interceptor) { Class<?> serviceApiType = GenericTypeResolver.resolveTypeArgument(interceptor.getClass(), ProviderSignInInterceptor.class); signInInterceptors.add(serviceApiType, interceptor); } /** * Process a sign-in form submission by commencing the process of establishing a connection to the provider on behalf of the user. * For OAuth1, fetches a new request token from the provider, temporarily stores it in the session, then redirects the user to the provider's site for authentication authorization. * For OAuth2, redirects the user to the provider's site for authentication authorization. * @param providerId the provider ID to authorize against * @param request the request * @return a RedirectView to the provider's authorization page or to the application's signin page if there is an error */ @RequestMapping(value="/{providerId}", method=RequestMethod.POST) public RedirectView signIn(@PathVariable String providerId, NativeWebRequest request) { ConnectionFactory<?> connectionFactory = connectionFactoryLocator.getConnectionFactory(providerId); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); preSignIn(connectionFactory, parameters, request); try { return new RedirectView(connectSupport.buildOAuthUrl(connectionFactory, request, parameters)); } catch (Exception e) { logger.error("Exception while building authorization URL: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process the authentication callback from an OAuth 1 service provider. * Called after the member authorizes the authentication, generally done once by having he or she click "Allow" in their web browser at the provider's site. * Handles the provider sign-in callback by first determining if a local user account is associated with the connected provider account. * If so, signs the local user in by delegating to {@link SignInAdapter#signIn(String, Connection, NativeWebRequest)} * If not, redirects the user to a signup page to create a new account with {@link ProviderSignInAttempt} context exposed in the HttpSession. * @param providerId the provider ID to authorize against * @param request the request * @return a RedirectView to the provider's authorization page or to the application's signin page if there is an error * @see ProviderSignInAttempt * @see ProviderSignInUtils */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="oauth_token") public RedirectView oauth1Callback(@PathVariable String providerId, NativeWebRequest request) { try { OAuth1ConnectionFactory<?> connectionFactory = (OAuth1ConnectionFactory<?>) connectionFactoryLocator.getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { logger.error("Exception while completing OAuth 1.0(a) connection: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process the authentication callback from an OAuth 2 service provider. * Called after the user authorizes the authentication, generally done once by having he or she click "Allow" in their web browser at the provider's site. * Handles the provider sign-in callback by first determining if a local user account is associated with the connected provider account. * If so, signs the local user in by delegating to {@link SignInAdapter#signIn(String, Connection, NativeWebRequest)}. * If not, redirects the user to a signup page to create a new account with {@link ProviderSignInAttempt} context exposed in the HttpSession. * @see ProviderSignInAttempt * @see ProviderSignInUtils * @param providerId the provider ID to authorize against * @param code the OAuth 2 authorization code * @param request the web request * @return A RedirectView to the target page or the signInUrl if an error occurs */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="code") public RedirectView oauth2Callback(@PathVariable String providerId, @RequestParam("code") String code, NativeWebRequest request) { try { OAuth2ConnectionFactory<?> connectionFactory = (OAuth2ConnectionFactory<?>) connectionFactoryLocator.getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { logger.error("Exception while completing OAuth 2 connection: ", e); return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString()); } } /** * Process an error callback from an OAuth 2 authorization as described at http://tools.ietf.org/html/rfc6749#section-4.1.2.1. * Called after upon redirect from an OAuth 2 provider when there is some sort of error during authorization, typically because the user denied authorization. * Simply carries the error parameters through to the sign-in page. * @param providerId The Provider ID * @param error An error parameter sent on the redirect from the provider * @param errorDescription An optional error description sent from the provider * @param errorUri An optional error URI sent from the provider * @param request The web request * @return a RedirectView to the signInUrl */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="error") public RedirectView oauth2ErrorCallback(@PathVariable String providerId, @RequestParam("error") String error, @RequestParam(value="error_description", required=false) String errorDescription, @RequestParam(value="error_uri", required=false) String errorUri, NativeWebRequest request) { logger.warn("Error during authorization: " + error); URIBuilder uriBuilder = URIBuilder.fromUri(signInUrl).queryParam("error", error); if (errorDescription != null ) { uriBuilder.queryParam("error_description", errorDescription); } if (errorUri != null ) { uriBuilder.queryParam("error_uri", errorUri); } return redirect(uriBuilder.build().toString()); } /** * Process the authentication callback when neither the oauth_token or code parameter is given, likely indicating that the user denied authorization with the provider. * Redirects to application's sign in URL, as set in the signInUrl property. * @return A RedirectView to the sign in URL */ @RequestMapping(value="/{providerId}", method=RequestMethod.GET) public RedirectView canceledAuthorizationCallback() { return redirect(signInUrl); } // From InitializingBean public void afterPropertiesSet() throws Exception { this.connectSupport = new ConnectSupport(sessionStrategy); this.connectSupport.setUseAuthenticateUrl(true); if (this.applicationUrl != null) { this.connectSupport.setApplicationUrl(applicationUrl); } }; // internal helpers private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory, NativeWebRequest request) { List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection); if (userIds.size() == 0) { ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection, connectionFactoryLocator, usersConnectionRepository); sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt); return redirect(signUpUrl); } else if (userIds.size() == 1) { usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection); String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request); postSignIn(connectionFactory, connection, (WebRequest) request); return originalUrl != null ? redirect(originalUrl) : redirect(postSignInUrl); } else { return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "multiple_users").build().toString()); } } private RedirectView redirect(String url) { return new RedirectView(url, true); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void preSignIn(ConnectionFactory<?> connectionFactory, MultiValueMap<String, String> parameters, WebRequest request) { for (ProviderSignInInterceptor interceptor : interceptingSignInTo(connectionFactory)) { interceptor.preSignIn(connectionFactory, parameters, request); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void postSignIn(ConnectionFactory<?> connectionFactory, Connection<?> connection, WebRequest request) { for (ProviderSignInInterceptor interceptor : interceptingSignInTo(connectionFactory)) { interceptor.postSignIn(connection, request); } } private List<ProviderSignInInterceptor<?>> interceptingSignInTo(ConnectionFactory<?> connectionFactory) { Class<?> serviceType = GenericTypeResolver.resolveTypeArgument(connectionFactory.getClass(), ConnectionFactory.class); List<ProviderSignInInterceptor<?>> typedInterceptors = signInInterceptors.get(serviceType); if (typedInterceptors == null) { typedInterceptors = Collections.emptyList(); } return typedInterceptors; } }
{ "task_name": "lcc" }
/* */ package edu.drexel.cis.dragon.ir.classification; /* */ /* */ import edu.drexel.cis.dragon.ir.classification.featureselection.FeatureSelector; /* */ import edu.drexel.cis.dragon.ir.classification.multiclass.CodeMatrix; /* */ import edu.drexel.cis.dragon.ir.classification.multiclass.HingeLoss; /* */ import edu.drexel.cis.dragon.ir.classification.multiclass.LossMultiClassDecoder; /* */ import edu.drexel.cis.dragon.ir.classification.multiclass.MultiClassDecoder; /* */ import edu.drexel.cis.dragon.ir.classification.multiclass.OVACodeMatrix; /* */ import edu.drexel.cis.dragon.ir.index.IRDoc; /* */ import edu.drexel.cis.dragon.ir.index.IndexReader; /* */ import edu.drexel.cis.dragon.matrix.DenseMatrix; /* */ import edu.drexel.cis.dragon.matrix.Row; /* */ import edu.drexel.cis.dragon.matrix.SparseMatrix; /* */ import java.io.FileInputStream; /* */ import java.io.FileOutputStream; /* */ import java.io.ObjectInputStream; /* */ import java.io.ObjectOutputStream; /* */ import java.util.ArrayList; /* */ import jnisvmlight.KernelParam; /* */ import jnisvmlight.LabeledFeatureVector; /* */ import jnisvmlight.LearnParam; /* */ import jnisvmlight.SVMLightInterface; /* */ import jnisvmlight.SVMLightModel; /* */ import jnisvmlight.TrainingParameters; /* */ /* */ public class SVMLightClassifier extends AbstractClassifier /* */ { /* */ private SVMLightModel[] arrModel; /* */ private LearnParam learnParam; /* */ private KernelParam kernelParam; /* */ private CodeMatrix codeMatrix; /* */ private MultiClassDecoder classDecoder; /* */ private double[] arrConfidence; /* */ private boolean scale; /* */ /* */ public SVMLightClassifier(String modelFile) /* */ { /* */ try /* */ { /* 34 */ ObjectInputStream oin = new ObjectInputStream(new FileInputStream(modelFile)); /* 35 */ this.arrModel = new SVMLightModel[oin.readInt()]; /* 36 */ for (int i = 0; i < this.arrModel.length; i++) /* 37 */ this.arrModel[i] = ((SVMLightModel)oin.readObject()); /* 38 */ this.codeMatrix = ((CodeMatrix)oin.readObject()); /* 39 */ this.classDecoder = ((MultiClassDecoder)oin.readObject()); /* 40 */ this.classNum = oin.readInt(); /* 41 */ this.scale = oin.readBoolean(); /* 42 */ this.featureSelector = ((FeatureSelector)oin.readObject()); /* 43 */ this.arrLabel = new String[this.classNum]; /* 44 */ for (int i = 0; i < this.arrLabel.length; i++) /* 45 */ this.arrLabel[i] = ((String)oin.readObject()); /* */ } /* */ catch (Exception e) { /* 48 */ e.printStackTrace(); /* */ } /* */ } /* */ /* */ public SVMLightClassifier(IndexReader indexReader) { /* 53 */ super(indexReader); /* 54 */ this.learnParam = new LearnParam(); /* 55 */ this.kernelParam = new KernelParam(); /* 56 */ this.classDecoder = new LossMultiClassDecoder(new HingeLoss()); /* 57 */ this.codeMatrix = new OVACodeMatrix(1); /* 58 */ this.classNum = 0; /* 59 */ this.scale = false; /* */ } /* */ /* */ public SVMLightClassifier(SparseMatrix doctermMatrix) { /* 63 */ super(doctermMatrix); /* 64 */ this.learnParam = new LearnParam(); /* 65 */ this.kernelParam = new KernelParam(); /* 66 */ this.classDecoder = new LossMultiClassDecoder(new HingeLoss()); /* 67 */ this.codeMatrix = new OVACodeMatrix(1); /* 68 */ this.classNum = 0; /* 69 */ this.scale = false; /* */ } /* */ /* */ public SVMLightClassifier(DenseMatrix doctermMatrix) { /* 73 */ super(doctermMatrix); /* 74 */ this.learnParam = new LearnParam(); /* 75 */ this.kernelParam = new KernelParam(); /* 76 */ this.classDecoder = new LossMultiClassDecoder(new HingeLoss()); /* 77 */ this.codeMatrix = new OVACodeMatrix(1); /* 78 */ this.classNum = 0; /* 79 */ this.scale = false; /* */ } /* */ /* */ public void setUseLinearKernel() { /* 83 */ this.kernelParam.kernel_type = 0L; /* */ } /* */ /* */ public void setUseRBFKernel() { /* 87 */ this.kernelParam.kernel_type = 2L; /* */ } /* */ /* */ public void setUsePolynomialKernel() { /* 91 */ this.kernelParam.kernel_type = 1L; /* */ } /* */ /* */ public void setUserSigmoidKernel() { /* 95 */ this.kernelParam.kernel_type = 3L; /* */ } /* */ /* */ public void setScalingOption(boolean option) /* */ { /* 103 */ this.scale = option; /* */ } /* */ /* */ public void setCodeMatrix(CodeMatrix matrix) /* */ { /* 111 */ this.codeMatrix = matrix; /* */ } /* */ /* */ public void setMultiClassDecoder(MultiClassDecoder decoder) /* */ { /* 119 */ this.classDecoder = decoder; /* */ } /* */ /* */ public int[] rank() { /* 123 */ return this.classDecoder.rank(); /* */ } /* */ /* */ public void train(DocClassSet trainingDocSet) /* */ { /* 133 */ if ((this.indexReader == null) && (this.sparseMatrix == null) && (this.denseMatrix == null)) { /* 134 */ return; /* */ } /* */ try /* */ { /* 138 */ trainFeatureSelector(trainingDocSet); /* 139 */ this.arrLabel = new String[trainingDocSet.getClassNum()]; /* 140 */ for (int i = 0; i < trainingDocSet.getClassNum(); i++) /* 141 */ this.arrLabel[i] = trainingDocSet.getDocClass(i).getClassName(); /* 142 */ this.classNum = trainingDocSet.getClassNum(); /* 143 */ this.codeMatrix.setClassNum(this.classNum); /* 144 */ ArrayList[] arrClass = new ArrayList[this.classNum]; /* 145 */ TrainingParameters param = new TrainingParameters(this.learnParam, this.kernelParam); /* 146 */ SVMLightInterface svm = new SVMLightInterface(); /* 147 */ this.arrModel = new SVMLightModel[this.codeMatrix.getClassifierNum()]; /* 148 */ for (int i = 0; i < this.classNum; i++) { /* 149 */ arrClass[i] = loadData(trainingDocSet.getDocClass(i)); /* */ } /* 151 */ for (int i = 0; i < this.codeMatrix.getClassifierNum(); i++) { /* 152 */ LabeledFeatureVector[] arrDoc = loadData(arrClass, this.codeMatrix, i); /* */ int posNum; /* 153 */ int negNum = posNum = 0; /* 154 */ for (int j = 0; j < arrDoc.length; j++) { /* 155 */ if (arrDoc[j].getLabel() > 0.0D) /* 156 */ posNum++; /* */ else { /* 158 */ negNum++; /* */ } /* */ } /* 161 */ param.getLearningParameters().svm_costratio = 1.0D; /* 162 */ this.arrModel[i] = svm.trainModel(arrDoc, param); /* */ } /* */ } /* */ catch (Exception e) { /* 166 */ e.printStackTrace(); /* */ } /* */ } /* */ /* */ public int classify(Row doc) /* */ { /* 174 */ if (this.arrModel == null) /* 175 */ return -1; /* 176 */ LabeledFeatureVector example = loadData(doc); /* 177 */ if (example == null) /* 178 */ return -1; /* 179 */ if ((this.arrConfidence == null) || (this.arrConfidence.length != this.codeMatrix.getClassifierNum())) /* 180 */ this.arrConfidence = new double[this.codeMatrix.getClassifierNum()]; /* 181 */ for (int j = 0; j < this.codeMatrix.getClassifierNum(); j++) /* 182 */ this.arrConfidence[j] = this.arrModel[j].classify(example); /* 183 */ return this.classDecoder.decode(this.codeMatrix, this.arrConfidence); /* */ } /* */ /* */ public double[] getBinaryClassifierConfidence() { /* 187 */ return this.arrConfidence; /* */ } /* */ /* */ public void saveModel(String modelFile) /* */ { /* */ try /* */ { /* 195 */ if (this.arrModel == null) /* 196 */ return; /* 197 */ ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(modelFile)); /* 198 */ out.writeInt(this.arrModel.length); /* 199 */ for (int i = 0; i < this.arrModel.length; i++) { /* 200 */ this.arrModel[i].removeTrainingData(); /* 201 */ out.writeObject(this.arrModel[i]); /* */ } /* 203 */ out.writeObject(this.codeMatrix); /* 204 */ out.writeObject(this.classDecoder); /* 205 */ out.writeInt(this.classNum); /* 206 */ out.writeBoolean(this.scale); /* 207 */ out.writeObject(this.featureSelector); /* 208 */ for (int i = 0; i < this.classNum; i++) /* 209 */ out.writeObject(getClassLabel(i)); /* 210 */ out.flush(); /* 211 */ out.close(); /* */ } /* */ catch (Exception e) { /* 214 */ e.printStackTrace(); /* */ } /* */ } /* */ /* */ private LabeledFeatureVector[] loadData(ArrayList[] arrClass, CodeMatrix matrix, int classifierIndex) /* */ { /* 223 */ ArrayList list = new ArrayList(); /* 224 */ for (int i = 0; i < this.classNum; i++) { /* 225 */ int label = this.codeMatrix.getCode(i, classifierIndex); /* 226 */ if (label != 0) /* */ { /* 229 */ for (int j = 0; j < arrClass[i].size(); j++) { /* 230 */ LabeledFeatureVector curDoc = (LabeledFeatureVector)arrClass[i].get(j); /* 231 */ curDoc.setLabel(label); /* 232 */ list.add(curDoc); /* */ } /* */ } /* */ } /* 236 */ LabeledFeatureVector[] all = new LabeledFeatureVector[list.size()]; /* 237 */ for (int j = 0; j < list.size(); j++) { /* 238 */ all[j] = ((LabeledFeatureVector)list.get(j)); /* */ } /* 240 */ list.clear(); /* 241 */ return all; /* */ } /* */ /* */ private ArrayList loadData(DocClass docs) /* */ { /* 249 */ ArrayList list = new ArrayList(docs.getDocNum()); /* 250 */ for (int i = 0; i < docs.getDocNum(); i++) { /* 251 */ LabeledFeatureVector curDoc = loadData(getRow(docs.getDoc(i).getIndex())); /* 252 */ if (curDoc != null) { /* 253 */ list.add(curDoc); /* */ } /* */ } /* 256 */ return list; /* */ } /* */ /* */ protected LabeledFeatureVector loadData(Row doc) /* */ { /* 265 */ if (doc == null) { /* 266 */ return null; /* */ } /* 268 */ int num = 0; /* 269 */ for (int j = 0; j < doc.getNonZeroNum(); j++) { /* 270 */ if (this.featureSelector.map(doc.getNonZeroColumn(j)) >= 0) { /* 271 */ num++; /* */ } /* */ } /* 274 */ if (num == 0) { /* 275 */ return null; /* */ } /* */ /* 278 */ int[] ids = new int[num]; /* 279 */ double[] values = new double[num]; /* 280 */ num = 0; /* 281 */ for (int j = 0; j < doc.getNonZeroNum(); j++) { /* 282 */ int newIndex = this.featureSelector.map(doc.getNonZeroColumn(j)); /* 283 */ if (newIndex >= 0) { /* 284 */ ids[num] = (newIndex + 1); /* 285 */ values[num] = doc.getNonZeroDoubleScore(j); /* 286 */ num++; /* */ } /* */ } /* */ /* 290 */ if (this.scale) { /* 291 */ double sum = 0.0D; /* 292 */ for (int j = 0; j < num; j++) { /* 293 */ sum += values[j] * values[j]; /* 294 */ sum = Math.sqrt(sum); /* 295 */ for (j = 0; j < num; j++) { /* 296 */ values[j] /= sum; /* */ } /* */ } /* */ } /* 300 */ return new LabeledFeatureVector(1.0D, ids, values); /* */ } /* */ } /* Location: C:\dragontoolikt\dragontool.jar * Qualified Name: dragon.ir.classification.SVMLightClassifier * JD-Core Version: 0.6.2 */
{ "task_name": "lcc" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdigEngine.Extensions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Markdig.Helpers; using Markdig.Parsers; using Markdig.Syntax; using Microsoft.DocAsCode.Common; public class QuoteSectionNoteParser : BlockParser { private List<string> _noteTypes = new List<string>{ "[!NOTE]", "[!TIP]", "[!WARNING]", "[!IMPORTANT]", "[!CAUTION]" }; public QuoteSectionNoteParser() { OpeningCharacters = new[] { '>' }; } public override BlockState TryOpen(BlockProcessor processor) { if (processor.IsCodeIndent) { return BlockState.None; } var column = processor.Column; var sourcePosition = processor.Start; var quoteChar = processor.CurrentChar; var c = processor.NextChar(); if (c.IsSpaceOrTab()) { processor.NextColumn(); } var rawNewBlock = new QuoteSectionNoteBlock(this) { QuoteChar = quoteChar, Column = column, Span = new SourceSpan(sourcePosition, processor.Line.End), }; TryParseFromLine(processor, rawNewBlock); processor.NewBlocks.Push(rawNewBlock); if (rawNewBlock.QuoteType == QuoteSectionNoteType.DFMVideo) { return BlockState.BreakDiscard; } else { return BlockState.Continue; } } public override BlockState TryContinue(BlockProcessor processor, Block block) { if (processor.IsCodeIndent) { return BlockState.None; } var quote = (QuoteSectionNoteBlock)block; var column = processor.Column; if (quote.QuoteType == QuoteSectionNoteType.DFMVideo) { return BlockState.BreakDiscard; } var c = processor.CurrentChar; if (c != quote.QuoteChar) { return processor.IsBlankLine ? BlockState.BreakDiscard : BlockState.None; } c = processor.NextChar(); // Skip opening char if (c.IsSpace()) { processor.NextChar(); // Skip following space } // Check for New DFM block if (TryParseFromLine(processor, new QuoteSectionNoteBlock(this))) { // Meet note or section, close this block, new block will be open in the next steps processor.GoToColumn(column); return BlockState.None; } else { block.UpdateSpanEnd(processor.Line.End); return BlockState.Continue; } } private bool TryParseFromLine(BlockProcessor processor, QuoteSectionNoteBlock block) { int originalColumn = processor.Column; block.QuoteType = QuoteSectionNoteType.MarkdownQuote; if (processor.CurrentChar != '[') { return false; } var stringBuilder = StringBuilderCache.Local(); var c = processor.CurrentChar; var hasExcape = false; while (c != '\0' && (c != ']' || hasExcape)) { if (c == '\\' && !hasExcape) { hasExcape = true; } else { stringBuilder.Append(c); hasExcape = false; } c = processor.NextChar(); } stringBuilder.Append(c); var infoString = stringBuilder.ToString().Trim(); if (c == '\0') { processor.GoToColumn(originalColumn); return false; } if (c == ']') { // "> [!NOTE] content" is invalid, go to end to see it. processor.NextChar(); while (processor.CurrentChar.IsSpaceOrTab()) processor.NextChar(); var isNoteVideoDiv = (infoString.StartsWith("[!div", StringComparison.OrdinalIgnoreCase)) || (infoString.StartsWith("[!Video", StringComparison.OrdinalIgnoreCase)) || IsNoteType(infoString); if (processor.CurrentChar != '\0' && isNoteVideoDiv) { Logger.LogWarning("Text in the first line of Note/Section/Video is not valid. Will be rendererd to <blockquote>"); processor.GoToColumn(originalColumn); return false; } } if (IsNoteType(infoString)) { block.QuoteType = QuoteSectionNoteType.DFMNote; block.NoteTypeString = infoString.Substring(2, infoString.Length - 3); return true; } if (infoString.StartsWith("[!div", StringComparison.OrdinalIgnoreCase)) { block.QuoteType = QuoteSectionNoteType.DFMSection; string attribute = infoString.Substring(5, infoString.Length - 6).Trim(); if (attribute.Length >= 2 && attribute.First() == '`' && attribute.Last() == '`') { block.SectionAttributeString = attribute.Substring(1, attribute.Length - 2).Trim(); } if (attribute.Length >= 1 && attribute.First() != '`' && attribute.Last() != '`') { block.SectionAttributeString = attribute; } return true; } if (infoString.StartsWith("[!Video", StringComparison.OrdinalIgnoreCase)) { string link = infoString.Substring(7, infoString.Length - 8); if (link.StartsWith(" http://") || link.StartsWith(" https://")) { block.QuoteType = QuoteSectionNoteType.DFMVideo; block.VideoLink = link.Trim(); return true; } } processor.GoToColumn(originalColumn); return false; } private bool IsRestLineEmpty(BlockProcessor processor, int movedCharCount) { int column = processor.Column; while (movedCharCount-- > 0) processor.NextChar(); while (processor.CurrentChar.IsSpaceOrTab()) processor.NextChar(); return processor.CurrentChar == '\0'; } private bool IsNoteType(string infoString) { foreach (var noteType in _noteTypes) { if (string.Equals(infoString, noteType, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } }
{ "task_name": "lcc" }
Passage 1: Gordon Wild Gordon Wild( born 16 October 1995) is a German footballer who currently plays for Major League Soccer club D.C. United. Passage 2: Simone Wild Simone Wild( born 7 December 1993) is a Swiss alpine ski racer. Passage 3: Stan Wild Stan Wild( born 19 February 1944) is a British gymnast. He competed at the 1968 Summer Olympics and the 1972 Summer Olympics. Passage 4: Blowing Wild Blowing Wild is a 1953 American drama film directed by Hugo Fregonese and starring Gary Cooper, Barbara Stanwyck and Anthony Quinn. It was written by Philip Yordan. The story revolves around a love triangle set in Mexico's oilfields, where bandits are still active. Ruth Roman also stars and adds to the romantic entanglements. Frankie Laine sang the title song, "Blowing Wild (The Ballad of Black Gold)", which was written by Dmitri Tiomkin, with lyrics by Paul Francis Webster. Passage 5: George Wild (footballer) George Wild( born 1887) was an English professional footballer who played as an inside right. Passage 6: Hugo Fregonese Hugo Geronimo Fregonese (April 8, 1908 in Mendoza – January 11, 1987 in Tigre) was an Argentine film director and screenwriter who worked both in Hollywood and his home country. He made his directorial debut in 1943. In 1949, he directed "Apenas un delincuente". Most of Fregonese's American films were Westerns and crime melodramas, like "Man in the Attic" (1953)" and Black Tuesday" (1954). He worked with such Hollywood actors as Gary Cooper, Barbara Stanwyck, Anthony Quinn, Edward G. Robinson, Luisa Vehil, Víctor Laplace, Soledad Silveyra, Paul Naschy and Joel McCrea, among others. For directing the now-almost forgotten film "My Six Convicts" (1952), Fregonese was nominated for the Directors Guild of America Award for Outstanding Directing - Feature Film. Passage 7: Pete Wild Pete Wild( born 1985) is an English football coach who manages FC Halifax Town. Passage 8: Ed Wild Ed Wild( born 1935) is a Canadian basketball player. He competed in the men's tournament at the 1956 Summer Olympics. Passage 9: Cody Wild Cody Wild( born June 5, 1987) is an American professional ice hockey defenseman. Passage 10: Michael Wild Michael Wild( born 27 March 1981) is an English former professional snooker player. Question: Where was the director of film Blowing Wild born? Answer: Mendoza
{ "task_name": "2WikiMultihopQA" }
Passage 1: Musselburgh railway station Musselburgh railway station is a railway station serving the town of Musselburgh, East Lothian near Edinburgh in Scotland. It was opened by British Rail in 1988 and is located on the East Coast Main Line, east of, and is served by the North Berwick Line. It is located near the recently built campus of the Queen Margaret University. A station of the same name was opened by North British Railway in July 1847 and was located not on the main line but alongside the River Esk. That station serviced the Edinburgh and Dalkeith line to Fisherrow but was closed to passenger services in 1964 and goods services in 1970. Passage 2: Baku railway station Baku Railway station is a railway station located in Baku, Azerbaijan. Passage 3: Ligovo railway station Ligovo railway station is a railway station located in St. Petersburg, Russia. Passage 4: Lamae railway station Lamae railway station is a railway station located in Lamae Subdistrict, Lamae District, Chumphon. It is a class 2 railway station located from Bangkok railway station. Passage 5: Bagatora railway station Bagatora railway station is a closed railway station located in Pakistan. Passage 6: Thepha railway station Thepha railway station is a railway station located in Thepha Subdistrict, Thepha District, Songkhla. It is a class 1 railway station located from Thon Buri railway station. Passage 7: Pai Khel railway station Pai Khel railway station is a Railway Station located in Pakistan. Passage 8: Gurap railway station Gurap railway station is a Kolkata Suburban Railway station on the Howrah- Bardhaman chord line operated by Eastern Railway zone of Indian Railways. It is situated beside Mogra- Gurup Road at Gurap in Hooghly district in the Indian state of West Bengal. Passage 9: Sawi railway station Sawi railway station is a railway station located in Na Pho Subdistrict, Sawi District, Chumphon. It is a class 2 railway station located from Bangkok railway station. Passage 10: Saphli railway station Saphli railway station is a railway station located in Saphli Subdistrict, Pathio District, Chumphon. It is a class 3 railway station located from Thon Buri railway station. Question: Are both Musselburgh Railway Station and Gurap Railway Station located in the same country? Answer: no
{ "task_name": "2WikiMultihopQA" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ package org.apache.directory.shared.kerberos.codec; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.directory.api.asn1.DecoderException; import org.apache.directory.api.asn1.EncoderException; import org.apache.directory.api.asn1.ber.Asn1Container; import org.apache.directory.api.asn1.ber.Asn1Decoder; import org.apache.directory.api.util.Strings; import org.apache.directory.shared.kerberos.codec.encryptedData.EncryptedDataContainer; import org.apache.directory.shared.kerberos.codec.types.EncryptionType; import org.apache.directory.shared.kerberos.components.EncryptedData; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test the EncryptedData decoder. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class EncryptedDataDecoderTest { /** * Test the decoding of a EncryptedData */ @Test public void testEncryptedData() { ByteBuffer stream = ByteBuffer.allocate( 0x16 ); stream.put( new byte[] { 0x30, 0x14, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x12, // ( byte ) 0xA1, 0x03, // kvno 0x02, 0x01, 0x05, // ( byte ) 0xA2, 0x08, // cipher 0x04, 0x06, 'a', 'b', 'c', 'd', 'e', 'f' } ); String decodedPdu = Strings.dumpBytes( stream.array() ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU try { Asn1Decoder.decode( stream, encryptedDataContainer ); } catch ( DecoderException de ) { fail( de.getMessage() ); } // Check the decoded EncryptedData EncryptedData encryptedData = ( ( EncryptedDataContainer ) encryptedDataContainer ).getEncryptedData(); assertEquals( EncryptionType.AES256_CTS_HMAC_SHA1_96, encryptedData.getEType() ); assertEquals( 5, encryptedData.getKvno() ); assertTrue( Arrays.equals( Strings.getBytesUtf8( "abcdef" ), encryptedData.getCipher() ) ); // Check the encoding ByteBuffer bb = ByteBuffer.allocate( encryptedData.computeLength() ); try { bb = encryptedData.encode( bb ); // Check the length assertEquals( 0x16, bb.limit() ); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { fail(); } } /** * Test the decoding of a EncryptedData with no kvno */ @Test public void testEncryptedDataNoKvno() { ByteBuffer stream = ByteBuffer.allocate( 0x11 ); stream.put( new byte[] { 0x30, 0x0F, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x12, // ( byte ) 0xA2, 0x08, // cipher 0x04, 0x06, 'a', 'b', 'c', 'd', 'e', 'f' } ); String decodedPdu = Strings.dumpBytes( stream.array() ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU try { Asn1Decoder.decode( stream, encryptedDataContainer ); } catch ( DecoderException de ) { fail( de.getMessage() ); } // Check the decoded EncryptedData EncryptedData encryptedData = ( ( EncryptedDataContainer ) encryptedDataContainer ).getEncryptedData(); assertEquals( EncryptionType.AES256_CTS_HMAC_SHA1_96, encryptedData.getEType() ); assertFalse( encryptedData.hasKvno() ); assertTrue( Arrays.equals( Strings.getBytesUtf8( "abcdef" ), encryptedData.getCipher() ) ); // Check the encoding ByteBuffer bb = ByteBuffer.allocate( encryptedData.computeLength() ); try { bb = encryptedData.encode( bb ); // Check the length assertEquals( 0x11, bb.limit() ); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { fail(); } } /** * Test the decoding of a EncryptedData with nothing in it */ @Test public void testEncryptedDataEmpty() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x02 ); stream.put( new byte[] { 0x30, 0x00 } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with no type */ @Test public void testEncryptedDataNoEType() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x04 ); stream.put( new byte[] { 0x30, 0x02, ( byte ) 0xA0, 0x00 // etype } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with a missing type */ @Test public void testEncryptedDataMissingEType() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x11 ); stream.put( new byte[] { 0x30, 0x0F, ( byte ) 0xA1, 0x03, // kvno 0x02, 0x01, 0x05, // ( byte ) 0xA2, 0x08, // cipher 0x04, 0x06, 'a', 'b', 'c', 'd', 'e', 'f' } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with an empty type */ @Test public void testEncryptedDataEmptyType() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x0B ); stream.put( new byte[] { 0x30, 0x04, ( byte ) 0xA0, 0x02, // etype 0x02, 0x00 // } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with an empty kvno */ @Test public void testEncryptedDataEmptyKvno() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x09 ); stream.put( new byte[] { 0x30, 0x07, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x01, // ( byte ) 0xA1, 0x00 // kvno } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with no cipher */ @Test public void testEncryptedDataNoCipher() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x0C ); stream.put( new byte[] { 0x30, 0x0A, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x01, // ( byte ) 0xA1, 0x02, // kvno 0x02, 0x01, 0x05 // } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData empty cipher */ @Test public void testEncryptedDataEmptyCipher() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x0E ); stream.put( new byte[] { 0x30, 0x0C, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x01, // ( byte ) 0xA1, 0x03, // kvno 0x02, 0x01, 0x01, // ( byte ) 0xA2, 0x00 // cipher } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } /** * Test the decoding of a EncryptedData with a null cipher */ @Test public void testEncryptedDataNullCipher() throws DecoderException { ByteBuffer stream = ByteBuffer.allocate( 0x10 ); stream.put( new byte[] { 0x30, 0x0E, ( byte ) 0xA0, 0x03, // etype 0x02, 0x01, 0x01, // ( byte ) 0xA1, 0x03, // kvno 0x02, 0x01, 0x01, // ( byte ) 0xA2, 0x02, // cipher 0x04, 0x00 } ); stream.flip(); // Allocate a EncryptedData Container Asn1Container encryptedDataContainer = new EncryptedDataContainer(); // Decode the EncryptedData PDU Assertions.assertThrows( DecoderException.class, () -> { Asn1Decoder.decode(stream, encryptedDataContainer); } ); } }
{ "task_name": "lcc" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Globalization { using System.Text; using System; using System.Diagnostics.Contracts; using System.Globalization; internal static class TimeSpanFormat { [System.Security.SecuritySafeCritical] // auto-generated private static String IntToString(int n, int digits) { return ParseNumbers.IntToString(n, 10, digits, '0', 0); } internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(false /*isNegative*/); internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/); internal enum Pattern { None = 0, Minimum = 1, Full = 2, } // // Format // // Actions: Main method called from TimeSpan.ToString // internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider) { if (format == null || format.Length == 0) format = "c"; // standard formats if (format.Length == 1) { char f = format[0]; if (f == 'c' || f == 't' || f == 'T') return FormatStandard(value, true, format, Pattern.Minimum); if (f == 'g' || f == 'G') { Pattern pattern; DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider); if (value._ticks < 0) format = dtfi.FullTimeSpanNegativePattern; else format = dtfi.FullTimeSpanPositivePattern; if (f == 'g') pattern = Pattern.Minimum; else pattern = Pattern.Full; return FormatStandard(value, false, format, pattern); } throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider)); } // // FormatStandard // // Actions: Format the TimeSpan instance using the specified format. // private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern) { StringBuilder sb = StringBuilderCache.Acquire(); int day = (int)(value._ticks / TimeSpan.TicksPerDay); long time = value._ticks % TimeSpan.TicksPerDay; if (value._ticks < 0) { day = -day; time = -time; } int hours = (int)(time / TimeSpan.TicksPerHour % 24); int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); int fraction = (int)(time % TimeSpan.TicksPerSecond); FormatLiterals literal; if (isInvariant) { if (value._ticks < 0) literal = NegativeInvariantFormatLiterals; else literal = PositiveInvariantFormatLiterals; } else { literal = new FormatLiterals(); literal.Init(format, pattern == Pattern.Full); } if (fraction != 0) { // truncate the partial second to the specified length fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff)); } // Pattern.Full: [-]dd.hh:mm:ss.fffffff // Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff] sb.Append(literal.Start); // [-] if (pattern == Pattern.Full || day != 0) { // sb.Append(day); // [dd] sb.Append(literal.DayHourSep); // [.] } // sb.Append(IntToString(hours, literal.hh)); // hh sb.Append(literal.HourMinuteSep); // : sb.Append(IntToString(minutes, literal.mm)); // mm sb.Append(literal.MinuteSecondSep); // : sb.Append(IntToString(seconds, literal.ss)); // ss if (!isInvariant && pattern == Pattern.Minimum) { int effectiveDigits = literal.ff; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction = fraction / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { sb.Append(literal.SecondFractionSep); // [.FFFFFFF] sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } } else if (pattern == Pattern.Full || fraction != 0) { sb.Append(literal.SecondFractionSep); // [.] sb.Append(IntToString(fraction, literal.ff)); // [fffffff] } // sb.Append(literal.End); // return StringBuilderCache.GetStringAndRelease(sb); } // // FormatCustomized // // Actions: Format the TimeSpan instance using the specified format. // internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) { Contract.Assert(dtfi != null, "dtfi == null"); int day = (int)(value._ticks / TimeSpan.TicksPerDay); long time = value._ticks % TimeSpan.TicksPerDay; if (value._ticks < 0) { day = -day; time = -time; } int hours = (int)(time / TimeSpan.TicksPerHour % 24); int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); int fraction = (int)(time % TimeSpan.TicksPerSecond); long tmp = 0; int i = 0; int tokenLen; StringBuilder result = StringBuilderCache.Acquire(); while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'h': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); DateTimeFormat.FormatDigits(result, hours, tokenLen); break; case 'm': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); DateTimeFormat.FormatDigits(result, minutes, tokenLen); break; case 's': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); DateTimeFormat.FormatDigits(result, seconds, tokenLen); break; case 'f': // // The fraction of a second in single-digit precision. The remaining digits are truncated. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); tmp = (long)fraction; tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen); result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture)); break; case 'F': // // Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); tmp = (long)fraction; tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen); int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (tmp % 10 == 0) { tmp = tmp / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } break; case 'd': // // tokenLen == 1 : Day as digits with no leading zero. // tokenLen == 2+: Day as digits with leading zero for single-digit days. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 8) throw new FormatException(Environment.GetResourceString("Format_InvalidString")); DateTimeFormat.FormatDigits(result, day, tokenLen, true); break; case '\'': case '\"': tokenLen = DateTimeFormat.ParseQuoteString(format, i); result.Append(format, i + 1, tokenLen - 2); break; case '%': // Optional format character. // For example, format string "%d" will print day // Most of the cases, "%" can be ignored. nextChar = DateTimeFormat.ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For example, "\d" will insert the character 'd' into the string. // nextChar = DateTimeFormat.ParseNextChar(format, i); if (nextChar >= 0) { result.Append(((char)nextChar)); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } break; default: throw new FormatException(Environment.GetResourceString("Format_InvalidString")); } i += tokenLen; } return StringBuilderCache.GetStringAndRelease(result); } internal struct FormatLiterals { internal String Start { get { return literals[0]; } } internal String DayHourSep { get { return literals[1]; } } internal String HourMinuteSep { get { return literals[2]; } } internal String MinuteSecondSep { get { return literals[3]; } } internal String SecondFractionSep { get { return literals[4]; } } internal String End { get { return literals[5]; } } internal String AppCompatLiteral; internal int dd; internal int hh; internal int mm; internal int ss; internal int ff; private String[] literals; /* factory method for static invariant FormatLiterals */ internal static FormatLiterals InitInvariant(bool isNegative) { FormatLiterals x = new FormatLiterals(); x.literals = new String[6]; x.literals[0] = isNegative ? "-" : String.Empty; x.literals[1] = "."; x.literals[2] = ":"; x.literals[3] = ":"; x.literals[4] = "."; x.literals[5] = String.Empty; x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep; x.dd = 2; x.hh = 2; x.mm = 2; x.ss = 2; x.ff = DateTimeFormat.MaxSecondsFractionDigits; return x; } // For the "v1" TimeSpan localized patterns, the data is simply literal field separators with // the constants guaranteed to include DHMSF ordered greatest to least significant. // Once the data becomes more complex than this we will need to write a proper tokenizer for // parsing and formatting internal void Init(String format, bool useInvariantFieldLengths) { literals = new String[6]; for (int i = 0; i < literals.Length; i++) literals[i] = String.Empty; dd = 0; hh = 0; mm = 0; ss = 0; ff = 0; StringBuilder sb = StringBuilderCache.Acquire(); bool inQuote = false; char quote = '\''; int field = 0; for (int i = 0; i < format.Length; i++) { switch (format[i]) { case '\'': case '\"': if (inQuote && (quote == format[i])) { /* we were in a quote and found a matching exit quote, so we are outside a quote now */ Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5"); if (field >= 0 && field <= 5) { literals[field] = sb.ToString(); sb.Length = 0; inQuote = false; } else { return; // how did we get here? } } else if (!inQuote) { /* we are at the start of a new quote block */ quote = format[i]; inQuote = true; } else { /* we were in a quote and saw the other type of quote character, so we are still in a quote */ } break; case '%': Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); goto default; case '\\': if (!inQuote) { i++; /* skip next character that is escaped by this backslash or percent sign */ break; } goto default; case 'd': if (!inQuote) { Contract.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 1; // DayHourSep dd++; } break; case 'h': if (!inQuote) { Contract.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 2; // HourMinuteSep hh++; } break; case 'm': if (!inQuote) { Contract.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 3; // MinuteSecondSep mm++; } break; case 's': if (!inQuote) { Contract.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 4; // SecondFractionSep ss++; } break; case 'f': case 'F': if (!inQuote) { Contract.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 5; // End ff++; } break; default: sb.Append(format[i]); break; } } Contract.Assert(field == 5); AppCompatLiteral = MinuteSecondSep + SecondFractionSep; Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); if (useInvariantFieldLengths) { dd = 2; hh = 2; mm = 2; ss = 2; ff = DateTimeFormat.MaxSecondsFractionDigits; } else { if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation. if (hh < 1 || hh > 2) hh = 2; if (mm < 1 || mm > 2) mm = 2; if (ss < 1 || ss > 2) ss = 2; if (ff < 1 || ff > 7) ff = 7; } StringBuilderCache.Release(sb); } } //end of struct FormatLiterals } }
{ "task_name": "lcc" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.olingo.commons.api.format; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import org.junit.Test; public class AcceptTypeTest { @Test public void wildcard() { List<AcceptType> atl = AcceptType.create("*/*"); assertEquals(1, atl.size()); assertEquals("*/*", atl.get(0).toString()); assertTrue(atl.get(0).matches(ContentType.create("a/a"))); assertTrue(atl.get(0).matches(ContentType.create("b/b"))); } @Test public void wildcardSubtype() { List<AcceptType> atl = AcceptType.create("a/*"); assertEquals(1, atl.size()); assertEquals("a/*", atl.get(0).toString()); assertTrue(atl.get(0).matches(ContentType.create("a/a"))); assertFalse(atl.get(0).matches(ContentType.create("b/b"))); } @Test public void singleAcceptType() { assertTrue(AcceptType.create("a/a").get(0).matches(ContentType.create("a/a"))); assertTrue(AcceptType.create("a/a;q=0.2").get(0).matches(ContentType.create("a/a"))); assertFalse(AcceptType.create("a/a;x=y;q=0.2").get(0).matches(ContentType.create("a/a"))); assertTrue(AcceptType.create("a/a;x=y;q=0.2").get(0).matches(ContentType.create("a/a;x=y"))); assertTrue(AcceptType.create("a/a; q=0.2").get(0).matches(ContentType.create("a/a"))); assertEquals("a/a;q=0.2;x=y", AcceptType.create("a/a;x=y;q=0.2").get(0).toString()); } @Test public void acceptTypes() { List<AcceptType> atl; atl = AcceptType.create("b/b,*/*,a/a,c/*"); assertNotNull(atl); assertTrue(atl.get(0).matches(ContentType.create("b/b"))); assertTrue(atl.get(1).matches(ContentType.create("a/a"))); assertEquals("c", atl.get(2).getType()); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(2).getSubtype()); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(3).getType()); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(3).getSubtype()); atl = AcceptType.create("a/a;q=0.3,*/*;q=0.1,b/b;q=0.2"); assertNotNull(atl); assertTrue(atl.get(0).matches(ContentType.create("a/a"))); assertTrue(atl.get(1).matches(ContentType.create("b/b"))); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(2).getType()); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(2).getSubtype()); atl = AcceptType.create("a/a;q=0.3,*/*;q=0.3"); assertNotNull(atl); assertTrue(atl.get(0).matches(ContentType.create("a/a"))); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(1).getType()); assertEquals(TypeUtil.MEDIA_TYPE_WILDCARD, atl.get(1).getSubtype()); atl = AcceptType.create("a/a;x=y;q=0.1,b/b;x=y;q=0.3"); assertNotNull(atl); assertTrue(atl.get(0).matches(ContentType.create("b/b;x=y"))); assertFalse(atl.get(0).matches(ContentType.create("b/b;x=z"))); assertTrue(atl.get(1).matches(ContentType.create("a/a;x=y"))); assertFalse(atl.get(1).matches(ContentType.create("a/a;x=z"))); atl = AcceptType.create("a/a; q=0.3, */*; q=0.1, b/b; q=0.2"); assertNotNull(atl); } @Test public void withQParameter() { List<AcceptType> acceptTypes = AcceptType.create("application/json;q=0.2"); assertEquals(1, acceptTypes.size()); final AcceptType acceptType = acceptTypes.get(0); assertEquals("application", acceptType.getType()); assertEquals("json", acceptType.getSubtype()); assertEquals("0.2", acceptType.getParameters().get(TypeUtil.PARAMETER_Q)); assertEquals("0.2", acceptType.getParameter(TypeUtil.PARAMETER_Q)); assertEquals(Float.valueOf(0.2F), acceptType.getQuality()); assertEquals("application/json;q=0.2", acceptType.toString()); } @Test public void formatErrors() { expectCreateError("/"); expectCreateError("//"); expectCreateError("///"); expectCreateError("a/b/c"); expectCreateError("a//b"); } @Test public void abbreviationsNotAllowed() { expectCreateError("application"); } @Test public void wildcardError() { expectCreateError("*/json"); } @Test public void wrongQParameter() { expectCreateError(" a/a;q=z "); expectCreateError("a/a;q=42"); expectCreateError("a/a;q=0.0001"); expectCreateError("a/a;q='"); expectCreateError("a/a;q=0.8,abc"); } @Test public void parameterErrors() { expectCreateError("a/b;parameter"); expectCreateError("a/b;parameter="); expectCreateError("a/b;name= value"); expectCreateError("a/b;=value"); expectCreateError("a/b;the name=value"); } @Test public void trailingSemicolon() { expectCreateError("a/b;"); } @Test public void fromContentType() { final List<AcceptType> acceptType = AcceptType.fromContentType(ContentType.APPLICATION_JSON); assertNotNull(acceptType); assertEquals(1, acceptType.size()); assertEquals(ContentType.APPLICATION_JSON.toContentTypeString(), acceptType.get(0).toString()); } private void expectCreateError(final String value) { try { AcceptType.create(value); fail("Expected exception not thrown."); } catch (final IllegalArgumentException e) { assertNotNull(e); } } @Test public void multipleTypeswithQParameter() { List<AcceptType> acceptTypes = AcceptType.create("application/json;q=0.2,application/json;q=0.2"); assertEquals(2, acceptTypes.size()); final AcceptType acceptType = acceptTypes.get(0); assertEquals("application", acceptType.getType()); assertEquals("json", acceptType.getSubtype()); assertEquals("0.2", acceptType.getParameters().get(TypeUtil.PARAMETER_Q)); assertEquals("0.2", acceptType.getParameter(TypeUtil.PARAMETER_Q)); assertEquals(Float.valueOf(0.2F), acceptType.getQuality()); assertEquals("application/json;q=0.2", acceptType.toString()); } @Test public void multipleTypeswithIllegalTypes() { List<AcceptType> acceptTypes = AcceptType.create("application/json;q=0.2,abc/xyz"); assertEquals(2, acceptTypes.size()); final AcceptType acceptType = acceptTypes.get(1); assertEquals("application", acceptType.getType()); assertEquals("json", acceptType.getSubtype()); assertEquals("0.2", acceptType.getParameters().get(TypeUtil.PARAMETER_Q)); assertEquals("0.2", acceptType.getParameter(TypeUtil.PARAMETER_Q)); assertEquals(Float.valueOf(0.2F), acceptType.getQuality()); assertEquals("application/json;q=0.2", acceptType.toString()); } @Test public void multipleFormatErrors() { expectCreateError("/,abc,a/a;parameter="); } @Test public void nullAcceptType() { expectCreateError(null); } @Test public void emptyAcceptType() { expectCreateError(""); } @Test public void noTypeAcceptType() { expectCreateError("/json"); } @Test public void withCharset() { List<AcceptType> acceptTypes = AcceptType.create("application/json;charset=utf-8"); assertEquals(1, acceptTypes.size()); final AcceptType acceptType = acceptTypes.get(0); assertEquals("application", acceptType.getType()); assertEquals("json", acceptType.getSubtype()); assertEquals("utf-8", acceptType.getParameter(ContentType.PARAMETER_CHARSET)); assertTrue(acceptType.matches(ContentType.create("application/json;" + "odata.metadata=minimal;charset=utf-8"))); assertFalse(acceptType.matches(ContentType.create("application/atom+xml;" + "odata.metadata=minimal;charset=utf-8"))); assertFalse(acceptType.matches(ContentType.create("application/json;" + "odata.metadata=minimal"))); } @Test public void withSubtypeStar1() { List<AcceptType> acceptTypes = AcceptType.create("application/json,application/*"); assertEquals(2, acceptTypes.size()); final AcceptType acceptType1 = acceptTypes.get(0); assertEquals("application", acceptType1.getType()); assertEquals("json", acceptType1.getSubtype()); final AcceptType acceptType2 = acceptTypes.get(1); assertEquals("application", acceptType2.getType()); assertEquals("*", acceptType2.getSubtype()); } @Test public void withSubtypeStar2() { List<AcceptType> acceptTypes = AcceptType.create("application/*,application/json"); assertEquals(2, acceptTypes.size()); final AcceptType acceptType1 = acceptTypes.get(0); assertEquals("application", acceptType1.getType()); assertEquals("json", acceptType1.getSubtype()); final AcceptType acceptType2 = acceptTypes.get(1); assertEquals("application", acceptType2.getType()); assertEquals("*", acceptType2.getSubtype()); } }
{ "task_name": "lcc" }
Passage 1: Still I Rise (album) Still I Rise is an album by 2Pac and the Outlawz which is released as the third posthumous studio album of 2Pac, and the first album by Outlawz as a group (not to be confused with their debut "Ride wit Us or Collide wit Us"). The album excludes some of the original line up of Outlawz and Hussein Fatal, who had left the group as he had refused to sign to Death Row. The album contains all previously unreleased, albeit remixed material. It was released on December 21, 1999, by Interscope Records. Passage 2: California Love "California Love" is a hip hop song by 2Pac featuring Dr. Dre and Roger Troutman. The song was released as 2Pac's comeback single after his release from prison in 1995 and was his first single as a Death Row Records artist. This is 2Pac's best-known song and his most successful, reaching number one on the "Billboard" Hot 100 for two weeks (as a double A-side single with "How Do U Want It") and 5 weeks at number one in New Zealand. The song was nominated for a posthumous Grammy Award as a Best Rap Solo Performance and Best Rap Performance by a Duo or Group (with Dr. Dre and Roger Troutman) in 1997. Passage 3: Hit 'Em Up "Hit 'Em Up" is a diss song by rap artist 2Pac featuring his group the Outlawz. It is the B-side to the single "How Do U Want It", released on June 4, 1996. The song’s lyrics contain vicious insults to several East Coast rappers, chief among them, Shakur's former friend turned rival, The Notorious B.I.G., also known as Biggie Smalls. The song was recorded in Los Angeles, California at Can Am Studios in May 1996. Reporter Chuck Philips, who interviewed Shakur at Can Am, described the song as "a caustic anti-East Coast crusade in which the rapper threatens to eliminate Biggie, Sean Combs (Puffy), and a slew of Bad Boy artists and other New York acts." The song was produced by long-time collaborator Johnny "J" and samples the bassline from "Don't Look Any Further" by Dennis Edwards and interpolates "Get Money" by Biggie Smalls group Junior M.A.F.I.A., which used the Dennis Edwards sample as well. The song's chorus contains an interpolation of Yellowman's 1982 hit reggae single 'Zungguzungguguzungguzeng'. The video, itself described as infamous, includes impersonations of Biggie, Puffy and Lil' Kim. Passage 4: 2 of Amerikaz Most Wanted "2 of Amerikaz Most Wanted" is a West Coast hip hop song written by 2Pac, Snoop Doggy Dogg and Daz Dillinger for 2Pac's 1996 double album "All Eyez on Me". The song is a duet performed by 2Pac and Snoop Dogg. "2 of Amerikaz Most Wanted" was released as promotional single and was the album's second single after "California Love". The song peaked at number 46 on the US "Billboard" Hot R&B/Hip-Hop Airplay chart. The song contains an interpolations of "The Message" by Grandmaster Flash and The Furious Five and "Radio Activity Rap (Let's Jam)" by MC Frosty and Lovin' C. Passage 5: Here to Save You All Here to Save You All is the debut album by rapper Chino XL released on April 9, 1996. It is predominantly produced by B Wiz and only held two guest appearances from Ras Kass and Kool Keith. It was produced mostly by Chino's close associates, and the lyrical content revolved around dark, hardcore themes (mostly metaphorical braggadoccio), dismissing the commercialized hip hop that was starting to gain momentum at this time. It contains the infamous but well-known song "Riiiot!" which had a line that possibly alluded to the rumor of West Coast rapper 2Pac being raped in prison. 2Pac later called him out on "Hit Em Up," and Chino responded with a freestyle dis. Chino himself stated that the line was not meant as a dis, and he and 2Pac were on good terms at the time of his death. Passage 6: Who Do U Believe In "Who Do U Believe In" is a posthumous single by 2Pac, released on a compilation album album. Song featuring: Yaki Kadafi, Nanci Fletcher, and Big Pimpin' Delemond. The song features a sample from Jamiroquai's Manifest Destiny.The single peaked at number 56 in the airplay chart. Passage 7: Yaki Kadafi Yafeu Akiyele Fula (October 9, 1977 – November 10, 1996), better known by his stage name Yaki Kadafi, was an American rapper who was best known as a founder and member of the rap groups Outlawz and Dramacydal. Kadafi's parents, Yaasmyn Fula and Sekou Odinga, were both members of the Black Panther Party. Fula, and Tupac Shakur's mother, Afeni Shakur, were close friends, and Kadafi and Tupac were friends until their deaths in 1996. Passage 8: Can't Sell Dope Forever Can't Sell Dope Forever is a collaboration studio album between Hip Hop groups dead prez and Outlawz. The album was released on Affluent Records July 25, 2006 and executive produced by Oscar Sanchez. Stic.man and M-1 of dead prez are most known for their revolutionary musical content, and E.D.I., Young Noble and Kastro of Outlawz are most known from their close affiliation with late Hip Hop superstar 2Pac. Passage 9: Tupac: Resurrection (soundtrack) Tupac: Resurrection was released by Amaru Entertainment as the soundtrack for the 2003 documentary, Academy Award nominated "". It includes several previously released 2Pac recordings, including "Death Around the Corner" from "Me Against the World", "Secretz of War" from "Still I Rise", Holler If Ya Hear Me from "Strictly 4 My N.I.G.G.A.Z." and "Rebel of the Underground" from "2Pacalypse Now"; and unreleased 2Pac verses re-constructed into new tracks such as "Ghost", "One Day at a Time", and "Runnin (Dying to Live)". Eminem produced major parts of this album. The song "Runnin (Dying to Live)" won the Top Soundtrack Song of the Year award at the 2005 ASCAP Rhythm & Soul Music Awards. The Album Features The Notorious B.I.G., Eminem, 50 Cent, Outlawz, & Digital Underground. "Intro", "Ghost", "Death Around The Corner", "Bury Me A G" and "Str8 Ballin'" do not actually feature in the movie, but appear on the album. Passage 10: Trapped (Tupac Shakur song) "Trapped" is a song by 2Pac that deals with police brutality. It was a single from his debut album, "2Pacalypse Now". The first verse tells a story of 2Pac being harassed by the police, one even shooting at him. He then fires back and says he did it because he was tired of constantly being profiled and abused by police officers. 2Pac then depicts the police chasing after him and eventually cornering him. He then ends the song with the line "I'd rather die then be trapped in the living hell", implying if forced into a corner he would rather die than live life in a cell. Question: Which member of Outlawz was featured on 2Pac's song Who Do U Believe In? Answer: Yaki Kadafi
{ "task_name": "hotpotqa" }
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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. */ /* * @author max */ package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.daemon.DaemonBundle; import com.intellij.codeInsight.daemon.GutterIconNavigationHandler; import com.intellij.codeInsight.navigation.ListBackgroundUpdaterTask; import com.intellij.ide.util.*; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.util.Computable; import com.intellij.psi.*; import com.intellij.psi.impl.FindSuperElementsHelper; import com.intellij.psi.presentation.java.ClassPresentationUtil; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiElementProcessorAdapter; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.search.searches.FunctionalExpressionSearch; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Function; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.MouseEvent; import java.text.MessageFormat; import java.util.*; public class MarkerType { private final GutterIconNavigationHandler<PsiElement> handler; private final Function<PsiElement, String> myTooltip; @NotNull private final String myDebugName; /** * @deprecated use {@link #MarkerType(String, Function, LineMarkerNavigator)} instead */ public MarkerType(@NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) { this("Unknown", tooltip, navigator); } public MarkerType(@NotNull String debugName, @NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) { myTooltip = tooltip; myDebugName = debugName; handler = new GutterIconNavigationHandler<PsiElement>() { @Override public void navigate(final MouseEvent e, final PsiElement elt) { DumbService.getInstance(elt.getProject()).withAlternativeResolveEnabled(() -> navigator.browse(e, elt)); } }; } @Override public String toString() { return myDebugName; } @NotNull public GutterIconNavigationHandler<PsiElement> getNavigationHandler() { return handler; } @NotNull public Function<PsiElement, String> getTooltip() { return myTooltip; } static final MarkerType OVERRIDING_METHOD = new MarkerType("OVERRIDING_METHOD", (NullableFunction<PsiElement, String>)element -> { PsiElement parent = getParentMethod(element); if (!(parent instanceof PsiMethod)) return null; PsiMethod method = (PsiMethod)parent; return calculateOverridingMethodTooltip(method, method != element.getParent()); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = getParentMethod(element); if (!(parent instanceof PsiMethod)) return; PsiMethod method = (PsiMethod)parent; navigateToOverridingMethod(e, method, method != element.getParent()); } }); static final MarkerType SIBLING_OVERRIDING_METHOD = new MarkerType("SIBLING_OVERRIDING_METHOD", (NullableFunction<PsiElement, String>)element -> { PsiElement parent = getParentMethod(element); if (!(parent instanceof PsiMethod)) return null; PsiMethod method = (PsiMethod)parent; return calculateOverridingSiblingMethodTooltip(method); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = getParentMethod(element); if (!(parent instanceof PsiMethod)) return; PsiMethod method = (PsiMethod)parent; navigateToSiblingOverridingMethod(e, method); } }); @Nullable private static String calculateOverridingMethodTooltip(@NotNull PsiMethod method, boolean acceptSelf) { PsiMethod[] superMethods = composeSuperMethods(method, acceptSelf); if (superMethods.length == 0) return null; PsiMethod superMethod = superMethods[0]; boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); final boolean sameSignature = superMethod.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY)); @NonNls final String key; if (isSuperAbstract && !isAbstract){ key = sameSignature ? "method.implements" : "method.implements.in"; } else{ key = sameSignature ? "method.overrides" : "method.overrides.in"; } return composeText(superMethods, "", DaemonBundle.message(key), IdeActions.ACTION_GOTO_SUPER); } @Nullable private static String calculateOverridingSiblingMethodTooltip(@NotNull PsiMethod method) { FindSuperElementsHelper.SiblingInfo pair = FindSuperElementsHelper.getSiblingInfoInheritedViaSubClass(method); if (pair == null) return null; PsiMethod superMethod = pair.superMethod; PsiClass subClass = pair.subClass; boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); String postfix = MessageFormat.format(" via sub-class <a href=\"#javaClass/{0}\">{0}</a>", ClassPresentationUtil.getNameForClass(subClass, true)); @NonNls String pattern = DaemonBundle.message(isSuperAbstract && !isAbstract ? "method.implements" : "method.overrides") + postfix; return composeText(new PsiElement[]{superMethod}, "", pattern, IdeActions.ACTION_GOTO_SUPER); } @NotNull private static String composeText(@NotNull PsiElement[] methods, @NotNull String start, @NotNull String pattern, @NotNull String actionId) { Shortcut[] shortcuts = ActionManager.getInstance().getAction(actionId).getShortcutSet().getShortcuts(); Shortcut shortcut = ArrayUtil.getFirstElement(shortcuts); String postfix = "<br><div style='margin-top: 5px'><font size='2'>Click"; if (shortcut != null) postfix += " or press " + KeymapUtil.getShortcutText(shortcut); postfix += " to navigate</font></div>"; return GutterIconTooltipHelper.composeText(Arrays.asList(methods), start, pattern, postfix); } private static void navigateToOverridingMethod(MouseEvent e, @NotNull PsiMethod method, boolean acceptSelf) { PsiMethod[] superMethods = composeSuperMethods(method, acceptSelf); if (superMethods.length == 0) return; boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(superMethods); PsiElementListNavigator.openTargets(e, superMethods, DaemonBundle.message("navigation.title.super.method", method.getName()), DaemonBundle.message("navigation.findUsages.title.super.method", method.getName()), new MethodCellRenderer(showMethodNames)); } private static void navigateToSiblingOverridingMethod(MouseEvent e, @NotNull PsiMethod method) { PsiMethod superMethod = FindSuperElementsHelper.getSiblingInheritedViaSubClass(method); if (superMethod == null) return; PsiElementListNavigator.openTargets(e, new NavigatablePsiElement[]{superMethod}, DaemonBundle.message("navigation.title.super.method", method.getName()), DaemonBundle.message("navigation.findUsages.title.super.method", method.getName()), new MethodCellRenderer(false)); } @NotNull private static PsiMethod[] composeSuperMethods(@NotNull PsiMethod method, boolean acceptSelf) { PsiElement[] superElements = FindSuperElementsHelper.findSuperElements(method); PsiMethod[] superMethods = ContainerUtil.map(superElements, element -> (PsiMethod)element, PsiMethod.EMPTY_ARRAY); if (acceptSelf) { superMethods = ArrayUtil.prepend(method, superMethods); } return superMethods; } private static PsiElement getParentMethod(@NotNull PsiElement element) { final PsiElement parent = element.getParent(); final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(parent); return interfaceMethod != null ? interfaceMethod : parent; } public static final String SEARCHING_FOR_OVERRIDING_METHODS = "Searching for Overriding Methods"; static final MarkerType OVERRIDDEN_METHOD = new MarkerType("OVERRIDDEN_METHOD", (NullableFunction<PsiElement, String>)element -> { PsiElement parent = element.getParent(); if (!(parent instanceof PsiMethod)) return null; PsiMethod method = (PsiMethod)parent; return getOverriddenMethodTooltip(method); }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof PsiMethod)) return; navigateToOverriddenMethod(e, (PsiMethod)parent); } }); private static String getOverriddenMethodTooltip(@NotNull PsiMethod method) { PsiElementProcessor.CollectElementsWithLimit<PsiMethod> processor = new PsiElementProcessor.CollectElementsWithLimit<>(5); OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter<>(processor)); boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); if (processor.isOverflow()){ return isAbstract ? DaemonBundle.message("method.is.implemented.too.many") : DaemonBundle.message("method.is.overridden.too.many"); } PsiMethod[] overridings = processor.toArray(PsiMethod.EMPTY_ARRAY); if (overridings.length == 0) { final PsiClass aClass = method.getContainingClass(); if (aClass != null && FunctionalExpressionSearch.search(aClass).findFirst() != null) { return "Has functional implementations"; } return null; } Comparator<PsiMethod> comparator = new MethodCellRenderer(false).getComparator(); Arrays.sort(overridings, comparator); String start = isAbstract ? DaemonBundle.message("method.is.implemented.header") : DaemonBundle.message("method.is.overriden.header"); @NonNls String pattern = "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#javaClass/{1}\">{1}</a>"; return composeText(overridings, start, pattern, IdeActions.ACTION_GOTO_IMPLEMENTATION); } private static void navigateToOverriddenMethod(MouseEvent e, @NotNull final PsiMethod method) { if (DumbService.isDumb(method.getProject())) { DumbService.getInstance(method.getProject()).showDumbModeNotification( "Navigation to overriding classes is not possible during index update"); return; } final PsiElementProcessor.CollectElementsWithLimit<PsiMethod> collectProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>()); final PsiElementProcessor.CollectElementsWithLimit<PsiFunctionalExpression> collectExprProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>()); final boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter<>(collectProcessor)); if (isAbstract && collectProcessor.getCollection().size() < 2) { final PsiClass aClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() { @Override public PsiClass compute() { return method.getContainingClass(); } }); if (aClass != null) { FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectExprProcessor)); } } }, SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) { return; } final PsiMethod[] methodOverriders = collectProcessor.toArray(PsiMethod.EMPTY_ARRAY); final List<NavigatablePsiElement> overridings = new ArrayList<>(); overridings.addAll(collectProcessor.getCollection()); overridings.addAll(collectExprProcessor.getCollection()); if (overridings.isEmpty()) return; boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(methodOverriders); MethodOrFunctionalExpressionCellRenderer renderer = new MethodOrFunctionalExpressionCellRenderer(showMethodNames); Collections.sort(overridings, renderer.getComparator()); final OverridingMethodsUpdater methodsUpdater = new OverridingMethodsUpdater(method, renderer); PsiElementListNavigator.openTargets(e, overridings.toArray(new NavigatablePsiElement[overridings.size()]), methodsUpdater.getCaption(overridings.size()), "Overriding methods of " + method.getName(), renderer, methodsUpdater); } private static final String SEARCHING_FOR_OVERRIDDEN_METHODS = "Searching for Overridden Methods"; static final MarkerType SUBCLASSED_CLASS = new MarkerType("SUBCLASSED_CLASS", (NullableFunction<PsiElement, String>)element -> { PsiElement parent = element.getParent(); if (!(parent instanceof PsiClass)) return null; PsiClass aClass = (PsiClass)parent; return getSubclassedClassTooltip(aClass); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { final PsiElement parent = element.getParent(); if (!(parent instanceof PsiClass)) return; final PsiClass aClass = (PsiClass)parent; navigateToSubclassedClass(e, aClass); } }); // Used in Kotlin, please don't make private public static String getSubclassedClassTooltip(@NotNull PsiClass aClass) { PsiElementProcessor.CollectElementsWithLimit<PsiClass> processor = new PsiElementProcessor.CollectElementsWithLimit<>(5, new THashSet<>()); ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(processor)); if (processor.isOverflow()) { return aClass.isInterface() ? DaemonBundle.message("interface.is.implemented.too.many") : DaemonBundle.message("class.is.subclassed.too.many"); } PsiClass[] subclasses = processor.toArray(PsiClass.EMPTY_ARRAY); if (subclasses.length == 0) { final PsiElementProcessor.CollectElementsWithLimit<PsiFunctionalExpression> functionalImplementations = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>()); FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(functionalImplementations)); if (!functionalImplementations.getCollection().isEmpty()) { return "Has functional implementations"; } return null; } Comparator<PsiClass> comparator = PsiClassListCellRenderer.INSTANCE.getComparator(); Arrays.sort(subclasses, comparator); String start = aClass.isInterface() ? DaemonBundle.message("interface.is.implemented.by.header") : DaemonBundle.message("class.is.subclassed.by.header"); @NonNls String pattern = "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#javaClass/{0}\">{0}</a>"; return composeText(subclasses, start, pattern, IdeActions.ACTION_GOTO_IMPLEMENTATION); } // Used in Kotlin, please don't make private public static void navigateToSubclassedClass(MouseEvent e, @NotNull final PsiClass aClass) { if (DumbService.isDumb(aClass.getProject())) { DumbService.getInstance(aClass.getProject()).showDumbModeNotification("Navigation to overriding methods is not possible during index update"); return; } final PsiElementProcessor.CollectElementsWithLimit<PsiClass> collectProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>()); final PsiElementProcessor.CollectElementsWithLimit<PsiFunctionalExpression> collectExprProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>()); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectProcessor)); if (collectProcessor.getCollection().size() < 2) { FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectExprProcessor)); } }, SEARCHING_FOR_OVERRIDDEN_METHODS, true, aClass.getProject(), (JComponent)e.getComponent())) { return; } final List<NavigatablePsiElement> inheritors = new ArrayList<>(); inheritors.addAll(collectProcessor.getCollection()); inheritors.addAll(collectExprProcessor.getCollection()); if (inheritors.isEmpty()) return; final PsiClassOrFunctionalExpressionListCellRenderer renderer = new PsiClassOrFunctionalExpressionListCellRenderer(); final SubclassUpdater subclassUpdater = new SubclassUpdater(aClass, renderer); Collections.sort(inheritors, renderer.getComparator()); PsiElementListNavigator.openTargets(e, inheritors.toArray(new NavigatablePsiElement[inheritors.size()]), subclassUpdater.getCaption(inheritors.size()), CodeInsightBundle.message("goto.implementation.findUsages.title", aClass.getName()), renderer, subclassUpdater); } private static class SubclassUpdater extends ListBackgroundUpdaterTask { private final PsiClass myClass; private final PsiClassOrFunctionalExpressionListCellRenderer myRenderer; private SubclassUpdater(@NotNull PsiClass aClass, @NotNull PsiClassOrFunctionalExpressionListCellRenderer renderer) { super(aClass.getProject(), SEARCHING_FOR_OVERRIDDEN_METHODS); myClass = aClass; myRenderer = renderer; } @Override public String getCaption(int size) { String suffix = isFinished() ? "" : " so far"; return myClass.isInterface() ? CodeInsightBundle.message("goto.implementation.chooserTitle", myClass.getName(), size, suffix) : DaemonBundle.message("navigation.title.subclass", myClass.getName(), size, suffix); } @Override public void run(@NotNull final ProgressIndicator indicator) { super.run(indicator); ClassInheritorsSearch.search(myClass, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() { @Override public SearchScope compute() { return myClass.getUseScope(); } }), true).forEach(new CommonProcessors.CollectProcessor<PsiClass>() { @Override public boolean process(final PsiClass o) { if (!updateComponent(o, myRenderer.getComparator())) { indicator.cancel(); } indicator.checkCanceled(); return super.process(o); } }); FunctionalExpressionSearch.search(myClass).forEach(new CommonProcessors.CollectProcessor<PsiFunctionalExpression>() { @Override public boolean process(final PsiFunctionalExpression expr) { if (!updateComponent(expr, myRenderer.getComparator())) { indicator.cancel(); } indicator.checkCanceled(); return super.process(expr); } }); } } private static class OverridingMethodsUpdater extends ListBackgroundUpdaterTask { private final PsiMethod myMethod; private final PsiElementListCellRenderer myRenderer; private OverridingMethodsUpdater(@NotNull PsiMethod method, @NotNull PsiElementListCellRenderer renderer) { super(method.getProject(), SEARCHING_FOR_OVERRIDING_METHODS); myMethod = method; myRenderer = renderer; } @Override public String getCaption(int size) { return myMethod.hasModifierProperty(PsiModifier.ABSTRACT) ? DaemonBundle.message("navigation.title.implementation.method", myMethod.getName(), size) : DaemonBundle.message("navigation.title.overrider.method", myMethod.getName(), size); } @Override public void run(@NotNull final ProgressIndicator indicator) { super.run(indicator); OverridingMethodsSearch.search(myMethod).forEach( new CommonProcessors.CollectProcessor<PsiMethod>() { @Override public boolean process(PsiMethod psiMethod) { if (!updateComponent(psiMethod, myRenderer.getComparator())) { indicator.cancel(); } indicator.checkCanceled(); return super.process(psiMethod); } }); final PsiClass psiClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() { @Override public PsiClass compute() { return myMethod.getContainingClass(); } }); FunctionalExpressionSearch.search(psiClass).forEach(new CommonProcessors.CollectProcessor<PsiFunctionalExpression>() { @Override public boolean process(final PsiFunctionalExpression expr) { if (!updateComponent(expr, myRenderer.getComparator())) { indicator.cancel(); } indicator.checkCanceled(); return super.process(expr); } }); } } }
{ "task_name": "lcc" }
Passage 1: Karl Anselm, 4th Prince of Thurn and Taxis Karl Anselm, 4th Prince of Thurn and Taxis, full German name: "Karl Anselm Fürst von Thurn und Taxis" (2 June 1733, Frankfurt am Main, Free Imperial City of Frankfurt, Holy Roman Empire – 13 November 1805, Winzer bei Regensburg, Electorate of Bavaria, Holy Roman Empire) was the fourth Prince of Thurn and Taxis, Postmaster General of the Imperial Reichspost, and Head of the Princely House of Thurn and Taxis from 17 March 1773 until his death on 13 November 1805. Karl Anselm served as "Prinzipalkommissar" at the Perpetual Imperial Diet in Regensburg for Joseph II, Holy Roman Emperor and Francis II, Holy Roman Emperor from 1773 to 1797. Passage 2: Crown of the Andes The Crown of the Immacculate Conception, known as the Crown of the Andes — known in Spanish as La Corona de los Andes and as "La Corona de Nuestra Señora de la Asunción de Popayán " — is a votive crown originally made for a larger than life-size statue of the Virgin in the cathedral of Popayán, Colombia. The diadem was made around 1660, and the arches were added around 1770. The crown purportedly includes emeralds taken from the captured Inca Emperor Atahualpa (1497–1533). In 1936, the crown was sold by its owners to an American businessman and it has remained in the United States ever since. As of December 2015, the crown belongs to the collection of the Metropolitan Museum of Art in New York City. Passage 3: List of Holy Roman Empresses Holy Roman Empress or Empress of the Holy Roman Empire is the title given to the consort (wife) or regent of the Holy Roman Emperor. The elective dignity of Holy Roman Emperor was restricted to males only, therefore there was never a Holy Roman Empress regnant, though women such as Theophanu or Maria Theresa of Austria, who controlled the power of rule, served as de facto Empresses regnant. Passage 4: Francis I, Holy Roman Emperor Francis I (German: "Franz Stefan" , French: "François Étienne" ; 8 December 1708 – 18 August 1765) was Holy Roman Emperor and Grand Duke of Tuscany, though his wife effectively executed the real powers of those positions. With his wife, Maria Theresa, he was the founder of the Habsburg-Lorraine dynasty. From 1728 until 1737 he was Duke of Lorraine. Francis traded the duchy to the ex-Polish king Stanisław Leszczyński in exchange for the Grand Duchy of Tuscany as one of the terms ending the War of the Polish Succession in November 1738. The duchy and the ducal title to Lorraine and Bar passed to King Louis XV of France upon Leszczynski's death in 1766, though Francis and his successors retained the right to style themselves as dukes of Lorraine and Bar. Passage 5: Leopold I, Holy Roman Emperor Leopold I (name in full: "Leopold Ignaz Joseph Balthasar Felician"; Hungarian: "I. Lipót" ; 9 June 1640 – 5 May 1705) was Holy Roman Emperor, King of Hungary, Croatia, and Bohemia. The second son of Ferdinand III, Holy Roman Emperor, by his first wife, Maria Anna of Spain, Leopold became heir apparent in 1654 by the death of his elder brother Ferdinand IV. Elected in 1658, Leopold ruled the Holy Roman Empire until his death in 1705. Passage 6: Concordat of Worms The Concordat of Worms (Latin: "Concordatum Wormatiense" ), sometimes called the Pactum Calixtinum by papal historians, was an agreement between Pope Calixtus II and Holy Roman Emperor Henry V on September 23, 1122, near the city of Worms. It brought to an end the first phase of the power struggle between the Papacy and the Holy Roman Emperors and has been interpreted as containing within itself the germ of nation-based sovereignty that would one day be confirmed in the Treaty of Westphalia (1648). In part this was an unforeseen result of strategic maneuvering between the Church and the European sovereigns over political control within their domains. The King was recognised as having the right to invest bishops with secular authority ("by the lance") in the territories they governed, but not with sacred authority ("by ring and staff"). The result was that bishops owed allegiance in worldly matters both to the pope and to the king, for they were obliged to affirm the right of the sovereign to call upon them for military support, under his oath of fealty. Previous Holy Roman Emperors had thought it their right, granted by God, to name Church officials within their territories (such as bishops) and to confirm the Papal election (and, at times of extraordinary urgency, actually name popes). In fact, the Emperors had been heavily relying on bishops for their secular administration, as they were not hereditary or quasi-hereditary nobility with family interests. A more immediate result of the Investiture struggle identified a proprietary right that adhered to sovereign territory, recognising the right of kings to income from the territory of a vacant diocese and a basis for justifiable taxation. These rights lay outside feudalism, which defined authority in a hierarchy of personal relations, with only a loose relation to territory. The pope emerged as a figure above and out of the direct control of the Holy Roman Emperor. Passage 7: Gerasim Zelić Gerasim Zelić (Serbian: Герасим Зелић ; 1752–1828) was a renowned Serbian Orthodox Church archimandrite, traveller and writer (a contemporary and compatriot of Dositej Obradović). His chief work is "Žitije" (Lives), in three volumes. They are memoirs of his travels throughout western Europe, Russia and Asia Minor from the latter half of the 18th century to the first decade of the 19th century and the famous personalities (Napoleon, Prince Eugène, Viceroy of Naples, Joseph II, Holy Roman Emperor, Leopold II, Holy Roman Emperor, Francis II, Holy Roman Emperor, Semyon Zorich, Catherine the Great, Alexander I of Russia, Stanisław August Poniatowski, Dositej Obradović) he met. He had valuable original notes on people, religions, manners, customs, trade, etc. Passage 8: La corona (Gluck) La corona ("The Crown") is an opera by the composer Christoph Willibald Gluck. It takes the form of an "azione teatrale" in one act. The Italian-language libretto is by Pietro Metastasio. The opera was intended to celebrate the name day of Emperor Francis I on 4 October 1765 but the emperor died in August and it remained unperformed until the 20th century. Passage 9: Maria Josepha of Bavaria Maria Josepha of Bavaria (Marie Josephe Antonie Walburga Felicitas Regula, 20 March 173928 May 1767) was Holy Roman Empress, Queen of the Romans, Archduchess of Austria, Grand Duchess of Tuscany, etc. by her marriage to Joseph II, Holy Roman Emperor. By birth, she was a Princess and Duchess of Bavaria as the daughter of Charles VII, Holy Roman Emperor, Elector of Bavaria, and Archduchess Maria Amalia of Austria. Passage 10: List of monarchs of Prussia The monarchs of Prussia were members of the House of Hohenzollern who were the hereditary rulers of the former German state of Prussia from its founding in 1525 as the Duchy of Prussia. The Duchy had evolved out of the Teutonic Order, a Roman Catholic crusader state and theocracy located along the eastern coast of the Baltic Sea. The Teutonic Knights were under the leadership of a Grand Master, the last of whom, Albert, converted to Protestantism and secularized the lands, which then became the Duchy of Prussia. The Duchy was initially a vassal of the Kingdom of Poland, as a result of the terms of the Prussian Homage whereby Albert was granted the Duchy as part of the terms of peace following the Prussian War. When the main line of Prussian Hohenzollerns died out in 1618, the Duchy passed to a different branch of the family, who also reigned as Electors of Brandenburg in the Holy Roman Empire. While still nominally two different territories, Prussia under the suzerainty of Poland and Brandenburg under the suzerainty of the Holy Roman Empire, the two states are known together historiographically as Brandenburg-Prussia. Following the Second Northern War, a series of treaties freed the Duchy of Prussia from any vassalage to any other state, making it a fully sovereign Duchy in its own right. This complex situation (where the Hohenzollern ruler of the independent Duchy of Prussia was also a subject of the Holy Roman Emperor as Elector of Brandenburg) laid the eventual groundwork for the establishment of the Kingdom of Prussia in 1701. For diplomatic reasons, the rulers of the state were known as the King in Prussia from 1701 to 1772; largely because they still owed fealty to the Emperor as Electors of Brandenburg, the "King in Prussia" title (as opposed to "King of Prussia") avoided offending the Emperor. As the Prussian state grew through several wars and diplomatic moves throughout the 18th century, it became apparent that Prussia had become a Great Power that did not need to submit meekly to the Holy Roman Empire. By 1772, the pretense was dropped, and the style "King of Prussia" was adopted. Thus it remained until 1871, when in the aftermath of the Franco-Prussian War, the King of Prussia Wilhelm I was crowned German Emperor. From that point forward, though the Kingdom of Prussia retained its status as a constituent state of the German Empire, all remaining Kings of Prussia also served as German Emperor, and that title took precedence. Question: In what year was the Holy Roman Emperor whose name day the opera "La corona" was intended to celebrate born? Answer: 1708
{ "task_name": "hotpotqa" }
Document: An unexpected increase in revenues, as documented by both the Administration in its Mid-Session Review and the Congressional Budget Office (CBO) in its August update has led to a renewed discussion of the effect of the 2001-2004 tax cuts on the economy and the possible feedback effects on revenue. The OMB Mid-Session Review also summarizes results from two Treasury studies indicating that tax cuts moved the economy out of the recession more quickly than would otherwise have been the case, and will encourage greater long-run economic growth. Some proponents of the tax cuts suggest that induced economic growth was large enough that taxes on the additional income more than offset the cost of the tax cuts, causing an increase rather than a decrease in revenues. Other observers doubt that economic growth was related to the tax cuts, or that it was large enough to significantly offset the cost of the cuts. After reviewing the data on the revenue increase, this report examines available economic studies, theory, and empirical data to assess the possible revenue feedback from the 2001-2004 tax cuts. Three major pieces of legislation constitute the bulk of these tax cuts. P.L. 107-16 , The Economic Growth and Tax Relief Reconciliation Act (referred to as EGTRRA) passed in 2001: its most important provisions were phased-in rate reductions, expansion of child credits, expansion of brackets and standard deductions for joint returns, and phaseout and eventual repeal of the estate tax. Most provisions were set to expire in 2010 (and some earlier), but some or all of them may be extended or made permanent. The main provision of The Job Creation and Worker Assistance Act of 2002 ( P.L. 107-47 ) was the adoption of bonus depreciation, which allowed a share of investment to be deducted immediately. P.L. 108-27 , The Jobs and Growth Tax Relief Reconciliation Act (JGTRRA), passed in 2003, accelerated the 2001 rate reductions, allowed lower tax rates for dividends and capital gains, and expanded and extended bonus depreciation. Bonus depreciation expired at the end of 2004, but there have been extensions of some other expiring provisions. The first section of this paper examines the data on revenues and growth that have given rise to these arguments. The next three sections discuss the three basic types of behavioral effects that might lead to increased (or decreased) revenues: short-run stimulus effects and the subsequent effects on the debt, "supply-side" effects that alter the amount of labor and capital in the economy, and shifts between taxable and tax-favored activities. The final section presents findings. The OMB Mid-Session Review projected revenues to be $115 billion higher than forecast in February, while CBO projected revenues $99 billion higher than its March forecast. According to CBO projections, the deficit will fall from 2.6% of GDP in FY2005 to 2.0% of GDP in FY2006. This revenue increase arose from increases in both individual and corporate income and followed an increase in 2005. In 2005, GDP grew by 6.5%, but revenues grew by 14.5%; in 2006 GDP is projected to grow by 6.6% and revenues by 11.6%. In 2005, revenues from social insurance taxes grew by 8.3%, revenues from individual income taxes by 14.6%, and revenues from corporate taxes by 47%. In 2006, CBO estimates revenues from social insurance taxes will grow by 5%, revenues from individual income taxes will grow by 14.3%, and revenues from corporate income taxes will grow by 22.2%. This growth in revenues is not due to any extraordinary growth of output, as the economy has been growing at rates typical of those following recoveries from previous recessions. Moreover, according to CBO, the economy has essentially reached its full employment level. Rather, the growth in revenues is due largely to an increase in taxes as a percentage of output. Most of the increase in taxes as a percentage of output is due to income taxes, with about 60% of the effect coming from the individual income tax and the remainder from the corporate tax. Table 1 reports, since 1990, the growth rate of real output and revenue from the corporate and individual income taxes as a percent of GDP as reported by CBO. Before discussing the data in this table, it is important to correct the data for a major effect from tax legislation, the introduction of bonus depreciation in 2002, its expansion in 2003, and its termination at the end of 2004. This provision is having effects on corporate tax revenue outside of economic performance. Bonus depreciation allowed depreciation deductions to occur earlier than they would have otherwise, thereby shifting revenue from the present to the future. Using the revenue estimates made at the time for bonus depreciation and another small tax issue having to do with losses, and assigning a share to corporations equal to the share of accelerated depreciation on equipment reported in the Joint Committee on Taxation's (JCT) tax expenditure estimates (79%), we correct the corporate tax ratio to see what it would have been without this legislative change. This number is reported in the last column. Using these figures, there no longer appears to be a significant growth in corporate tax revenues from 2005 to 2006. The effect of the depreciation change accounted for 84% of the faster growth in corporate tax revenues, and without it, corporate taxes would have grown by less than 9% rather than by 22%. (It accounts for slightly over half the 47% growth from 2004 to 2005.) This adjustment probably applies too much weight to bonus depreciation, however, because preliminary evidence through 2003 suggests the usage of bonus depreciation has not been as great as might have been predicted. Thus, the pattern adjusted for this legislative change probably falls between the two last columns of Table 1 . Nevertheless, adjusting even in part for this effect smooths out the general pattern of corporate taxes during the recession and recovery, with the shares during the recession and slow growth years similar to those in the early 1990s, and the shares now similar to the period prior to the recession in 2000/2001. Because at least part of the growth in corporate revenues can be explained by legislative changes, and because revenue from the individual income tax was a greater contributor to growth in general, the more important issue to focus on seems to be the growth in the individual income tax share. Some small part of the growth from 2005 to 2006 is also attributable to depreciation for unincorporated businesses, but in this case it accounts for only 14% of the faster growth in revenues based on the original revenue estimates. Policymakers are interested in the question of what, if any, part of the increasing individual income tax share is a result of economic stimulus brought about by the 2001-2004 tax cuts? The following discussion looks at this issue from a macroeconomic viewpoint. First, the fact that income taxes as a percentage of output rose does not necessarily mean that effect is due to growth effects arising from the tax cuts. If that were the case, one could also conclude that the rate increase in 1993 led to a growth in effective tax rates independent from the direct effects. The share of output collected in individual taxes continued to grow in the late 1990s after the tax rate increases were in place. This growth in the late 1990s generally reflected both an increase in the average effective tax rate on taxable income (which could arise from increasing inequality in incomes and real bracket creep), and increases in taxable income relative to GDP, which could reflect items such as faster growth in capital gains. Second, were there no similar growth effects following the 1993 tax cut, one could not empirically attribute the recent growth to a specific event because it is not possible to know what would have happened to the economy in the absence of the tax cut. To attribute the growth to the tax cut would be to presume that because one event occurs before another, the first event causes the second. When estimating the effect of tax changes, observing the aftermath really does not change our knowledge derived from observing economy wide changes except in a very marginal way. At best, it is one more observation, and in order to project economic changes we need enough observations to form an adequate statistical sample. Finally, CBO suggests (based on comparing withholding and other receipts) that the recent growth in revenue is not due to growth in wage income, which is the basic conduit through which most economic growth occurs in the short run, but through other routes. Any change in saving and investment induced by the tax cut (and it is not clear there is such a change) would have a negligible effect on the capital stock and output: this effect is a long-run phenomenon, not a short-run one. To think about the potential revenue offsets due to economic or behavioral change induced by a tax change, it is necessary to turn to a more general analysis of these effects. They can be separated into three types of effects: demand-side stimulus effects including the eventual consequences of increased debt, "supply-side" effects on labor and capital, and changes in the allocation of consumption and other forms of taxpayer avoidance. When the economy is in a recession, the demand-side effects of a tax cut can increase output. But do these demand-side effects suggest that a tax cut can pay for itself, or even partially pay for itself? Any effects on output from demand-side stimulus (or contraction) are transitory and the long-run effects are generally negative as the increased government borrowing from the tax cut is likely to crowd out private capital. Demand-side stimulus can have little effect on real output if enacted when the economy is at full employment; however, the 2001-2004 tax cuts took place when the economy was not at full employment. Since the tax cuts began in 2001, much of the demand-side effect has likely faded and will continue to fade, and any offsets would have been temporary and are now on the decline. In any case, they are not likely to explain the current increase in revenues which does not derive primarily from extraordinary growth in output but from an increase in the effective tax rate in the case of the individual tax and from the longer run consequences of bonus depreciation in the case of the corporate tax. As time goes on, assuming revenues are not fully recovered and as the stimulus fades, the effect of the tax cuts is to reduce output by reducing the capital stock from what it otherwise would have been, magnifying the deficit through growing interest payments and also reducing tax revenue from what it otherwise would have been by reducing output. In the long run a tax cut that results in added debt service, holding behavioral responses fixed, reduces output and leads to a larger revenue loss (depending on the timing of the tax cuts), and a considerably larger cost. For example, the cost of extending the 2001-2004 tax cuts and reforming the alternative minimum tax will be increased by about 14% over the first 10 years due to debt service. CBO reports that debt service would add 25% to the cost of an across-the-board tax cut over 10 years. It would require a much larger multiplier effect than is commonly presumed or found in macroeconomic models to fully or significantly offset the tax cut even on a temporary basis. If the marginal tax rate is 20%, as suggested in a recent Treasury analysis, then a tax cut would have to increase output by a multiplier of 5 in order to bring in enough revenue to offset the original tax cut, and even in the most optimistic of views, the multiplier is not this large. Economic theory suggests that fiscal policy may also be limited in its effect in an open economy if capital is relatively mobile. Expansionary fiscal policy induces an increase in interest rates that causes an inflow of capital, which in turn increases the exchange rate and reduces net exports. One of the Treasury Department's studies reported in the Mid-Session Review that its own simulations of the tax cuts, using the Macroeconomic Advisers (MA) model , resulted in an increase in output in 2004 of 3.5% to 4%. Given that the 2001-2004 tax cuts are estimated at about 1.4% of output, this Treasury analysis implies a multiplier of around 2.5 to 3, and a revenue offset of 50% to 60%, not 100%. But this multiplier effect is likely overstated and depends heavily on the response of the Federal Reserve. The monetary authorities have a range of potential actions. They can keep the interest rate fixed, which means they accommodate and enhance the fiscal stimulus. They can keep the money supply fixed, which means taking no action. They can keep the inflation rate and output level fixed, which means counteracting the fiscal policy. Gregory Mankiw, economics professor at Harvard and former chairman of the Council of Economic Advisors in the current Administration, reports the tax multiplier in a major macroeconomic model (Data Resources Inc., or DRI, a predecessor of DRI-WEFA, and in turn a predecessor of Global Insight) is 1.19 if the interest rate is held constant (which would require a monetary expansion), 0.26 if the money supply is held constant (the interest rate would rise but output could also rise), and zero if the inflation rate is held constant (the interest rate rises so much that output is fixed). There is some disagreement among economists on what the monetary authorities tend to do in response to fiscal expansion. Currently, two major private sector macroeconomic models (MA and Global Insight) tend to use a Taylor rule, which targets the real interest rate but has it rise as inflation and output increase. This policy expands the money supply to keep interest rates constant in the very short run but eventually allows the interest rate to rise. The multiplier for a lump sum tax change using this assumption, over four to eight quarters, is about 0.7 in the MA model and about 0.8 in the Global Insight model. A lump sum tax change tends to produce a larger effect than a change in the tax rate because none of the increased output is taxed. In the MA model, the effect fades to zero after about four years, while in the Global Insight Model it fades to zero after about eight years. A recent survey of multipliers by researchers at the International Monetary Fund (IMF) found that a proportional tax cut had a short-run multiplier of 0.6 and 0.7 in the two models it examines that estimate effects in the United States, the OECD Interlink and the IMF Multimodel, respectively. The first assumed real interest rates were fixed, the second that the money stock was fixed. Empirical estimates of multipliers also tended to find tax multipliers less than one. There is apparently no report or study available to determine what assumptions were made in the Treasury simulation to produce their results, and no strictly comparable studies that cover several years, all tax cuts, and are confined to demand-side effects. However, several related studies either done by the forecasting firms themselves or by congressional researchers suggest more modest effects. These studies are described in more detail in a recent CRS report, but for EGTRRA the MA model reported a 1.2% increase in the second half of 2001 and a 0.3% increase in 2002, while DRI-WEFA reported a 0.4% increase in the second half of 2001. JCT used a modified MA model and a Global Insight model to examine JGTRRA, that also included some supply-side effects and found a 0.2% increase in the first five years for MA and a 0.9% increase for Global Insight; output fell by 0.1% in the next five years. CBO, also using a model with supply-side effects, assessed the 2004 budget proposals which included JGTRRA and some other provisions, and found a 0.2% increase for the MA model and a 1.4% increase for the Global Insight model in the first three years, and negative effects in the following three. Using a value of the multiplier of 0.7, at the peak, the tax cuts would have recovered 14% (the tax rate times the multiplier) of the initial cost between the first and second years and the overall peak would have already passed, especially for the earlier tax cuts. (Of the combined tax cut, about 15% took place in 2001, around a quarter in each of the next two years and about a third in 2004, all in early or mid year.) They do not likely explain the increase in revenues projected for FY2006 as they amount to no more than 2/10 of a percent of GDP even at the peak, and the effect should be declining. A third issue is whether the short-run stimulus is unique to a tax cut. It is not a tax cut per se that stimulates the economy but rather an increase in the deficit which alternatively could be accomplished via spending increases. Indeed, spending multipliers are larger than tax multipliers. Mankiw reports spending multiplies in the DRI model at 1.93 with fixed interest rates and 0.6 at a fixed money supply, respectively 60% and 130% larger than the tax multiplier. In the OECD and IMF models, the spending multiplier was 1.1 in both models, or 60% to 80% larger than the tax rate multiplier. If revenue feedback were to be a justification, it would apply with greater force to spending increases than to tax cuts. Thus any revenue obtained from the feedback due to the stimulus effect could have also been obtained through expansionary fiscal policy via increased government spending. Both of these stimulative policies were in place during the recession and recovery. Further, the economy can be stimulated via monetary policy as well as fiscal policy, and monetary policy does not leave a residual debt and deficit that undermines capital formation. Monetary policy is also likely more powerful in an open economy. A second way in which behavioral response can lead to a feedback, either positive or negative, is through "supply-side" behavioral responses, that is, increases in labor supply and in the capital stock, and which are based on growth models. The OMB Mid-Session Review included a Treasury Department estimate of these effects, and the Treasury also prepared a separate study. This section examines that modeling exercise, and compares it with a previous one by Department of Treasury analysts estimating the effects of the tax reform proposals made by the President's Advisory Panel on Federal Tax Reform. As discussed below, the Treasury's analysis of the 2001 tax cut as compared to the analysis of the tax reform proposals has been changed by limiting the model type, but allowing sensitivity analysis with respect to elasticities (behavioral responses of labor supply to changes within that model). The Treasury analysis considers both short run and long-run effects. Macroeconomists note that the important behavioral response in the short run is the labor supply response, since even significant increases in saving can do little to affect the capital stock or output in the short run. If the labor supply effect is to completely offset the revenue cost in the short run, output must increase by 7% with a tax rate of 20%, and since labor accounts for about two-thirds of output, the labor supply would have to increase by over 10%. Government statistics do not show a change of this magnitude. The base case estimates in the Treasury study suggest that the induced effect on output were the tax cuts to be extended would lead to a revenue offset of 7% of the initial cost in the first five years and 10% in the long run. The models and modeling approaches used in the two studies differ in two important ways: limiting the type of model used to a single one and providing sensitivity analysis with respect to elasticities within that model. The earlier Department of the Treasury study used three types of models—a reduced form growth model (Solow model), and two intertemporal models, the overlapping generations model (OLG) and the Ramsey model (which treats the economy as an infinitely lived individual). The tax cut extension study uses only the OLG. This change is significant because the intertemporal models tend to yield much larger behavioral responses to changes in the tax on capital income than the reduced form growth models, especially in the short run. In the initial tax reform study of the consumption tax where there were significant changes in the capital income tax rates, the Solow model had the smallest result and the Ramsey model had the largest result. In the 10-year budget horizon, the Solow, OLG, and Ramsey models resulted in output increases of 0.1%, 1.5%, and 1.9% respectively. In the long-run steady state, the effects were 1.4%, 2.2%, and 4.8% respectively. It is difficult to determine how much of the difference between the OLG and Ramsey models is due to the elasticities, how much is due to some specific features that moderate the effects of the OLG model, and how much is due to the time horizon of the model. One can certainly make a case for preferring the OLG model, of the intertemporal models, because it does not require strict conditions to achieve an internal equilibrium (where a broad range of people hold assets). At the same time, one can also make a case for choosing a reduced form model (the Solow model). Intertemporal models present many problems. They involve some fairly heroic assumptions about the abilities of individuals to make complex decisions, including choosing work hours and consumption over a lifetime in response to tax changes and the general equilibrium consequences of those tax changes. Such a calculation is beyond the skill of most professional economists, much less the ordinary individual. Intertemporal models also have not been empirically tested. Much of the savings response reflects intertemporal substitution of labor in response to interest rate changes, where virtually no evidence of a response is available. Moreover, there is no evidence of the savings response for time periods that are very far apart, which largely drives the results in the model for savings. Alternative "rules of thumb" savings behavior may be more consistent with individual savings behavior and tend to imply a zero or negative elasticity. The savings rate has had a tendency to change little over much of history, as has the capital output ratio; all observations are consistent with an extremely small savings response. The second change in the Treasury analysis was the introduction, within the context of the OLG model, of different elasticities that could yield different magnitudes of response. This sensitivity analysis is very useful and has been little used in previous supply-side dynamic modeling experiments. Presented were a base case, a low case, and a high case. The base case elasticities were quite similar to the parameters used in the earlier study for the OLG model, but below those for the Ramsey model. In the earlier study of tax reform, the "static" substitution effect for labor (which determines the within-period labor supply response to changes in marginal tax rates on labor income) was around 0.5 in the Ramsey model, and 0.3 in the OLG model, with the former clearly much higher than standard estimates, and the latter still slightly toward the high side (these estimates would probably be between 0.2 and 0.3 , as discussed above). In the new study, this elasticity is set at around 0.3 in the base case, around 0.2 in the low case, and around 0.5 in the high case. The income elasticities (where tax cuts reduce labor supply) are all high. The intertemporal substitution elasticity for labor, which measures how labor is shifted over time in response to wage changes over time (and that also governs the response to interest rates even though this response has not been directly tested) was originally around 0.75 in the Ramsey model and around 0.49 in the OLG model. Under the current analysis, the estimates appear to be around 0.4 for the base case, around 0.2 for the low case, and around 0.75 for the high case. Most empirical evidence suggests that elasticity is quite small, around 0.2. The Department of the Treasury discussion implies that a similar measure would have been chosen for men, but that the intertemporal elasticity was increased to around 0.4 to reflect a presumably large intertemporal substitution elasticity for women. There appears to be no evidence of women's responses referred to in the study although women are generally believed to have a more elastic labor supply. However, one recent study that did estimate the intertemporal labor supply response of women found it to be not significantly different from zero. Since the Treasury paper is studying a tax cut, rather than a revenue neutral change, some assumption must be made as to how the revenue loss would be made up; otherwise one cannot solve an intertemporal model. Two assumptions were made: a cut in government spending after 10 years and an across-the-board increase in marginal and average tax rates after 10 years. The study also divided the effects into dividend and capital gains cuts, which had a relatively small but positive effect; the reductions of the top rates (which had the largest positive effects with spending cuts, reflecting the labor supply substitution effect); and the remaining extensions, which tended to be negative (with spending cuts) because of income effects. The overall effects are summarized in Table 2 . As this analysis suggests, the choice of elasticities can make a great deal of difference, reflecting the uncertainty about these responses. The empirical evidence discussed above actually supports the low case somewhat more. Note also that with tax increases, the effects are larger in the short run, but negative in the long run. This comparison illustrates the importance of the intertemporal substitution response, which is causing a shifting of labor into the present because of the temporarily higher wages in the next five years. Even in the context of an intertemporal model with relatively large behavioral responses, the effects are not very large. In this model, the fact that revenues must be made up by spending cuts clearly acknowledges that the tax cuts do not pay for themselves. But what is the magnitude? As noted earlier, the tax cut is about 1.4% of GDP. For the base case reported above, output increases by 0.5% in the short run and 0.7% in the long run when offset by spending increases. In the tax reform study, Treasury indicated the marginal tax rate on labor income was 24% and the marginal rate on capital income 14%. Using an overall rate of 20%, the offsetting revenue gain from induced economic effects would be 0.1% of output, or 7% of revenue loss in the next five years. It would be about 10% of revenue loss in the steady state. In the high case, it would be 18% in the short run and 24% in the long run. However, with the lower elasticity case, which seems more consistent with empirical evidence, it would be less than 1% in both the short and long run. There is a third type of empirical evidence which might be considered to assess revenue feedback effects, and that is empirical evidence that directly examines how taxable income changes in response to tax changes. This approach could, in theory, capture all of the feedback effects, but the empirical methodology used limits it to supply-side effects discussed above (labor response), and adds other behavioral responses, such as substituting taxable for tax exempt income (i.e., reducing fringe benefits relative to wages, or reducing charitable contributions when taxes are cut). Some of these latter effects are, however, already incorporated in conventional revenue estimates by the JCT. These studies use a "difference-in-difference" approach to estimating the taxable income response by comparing taxpayers who were subject to different tax rate changes and comparing their behavioral change. For example, if taxpayers in one group had no tax change and taxpayers in another who were similar (i.e., had income that was similar) had a tax change, a relative change in their taxable income could be ascribed to the tax difference, presuming they were otherwise affected by other common economic factors. Note that theoretically, one cannot be sure whether this effect is positive or negative, because of income and substitution effects. A tax cut's marginal effects may increase taxable income through increased labor supply or shifting into taxable forms, but the income effect may reduce labor supply or increase charitable contributions. In addition, a tax cut can shift income between corporate and noncorporate sources. As shown in the Appendix the feedback share effect is Et/(1-t), where E is the elasticity and t is the tax rate. With t at 0.20, the elasticity would have to be 4 to have a tax cut pay for itself and no study has found an elasticity of this level. Some of the earliest studies tended to find elasticities in excess of one, and even as high as three, but critics have identified some serious statistical problems with these studies that suggest their results not be considered. As these problems are technical in nature, they are discussed in more detail in the appendix, but essentially they arise because of failure to account for a trend in increasing inequality of income and failure to allow elasticities to vary across income classes. More recent studies have produced smaller elasticities that tend to be around 0.4, although even these estimates are subject to serious uncertainties (discussed briefly in the appendix as well) so that it is difficult to rely upon these later estimates. Moreover, while the studies are based on the marginal tax share, there would, in theory, be very different effects for different tax revisions because behavior is affected by average tax rates. For example, the 1981 tax cut was an across-the-board rate cut with some other changes, but the 1986 tax reform act preserved distributional neutrality. The 1990 and 1993 tax increases concentrated on very high incomes. The 2001-2004 tax cut, however, had significant income effects with little marginal effect on tax rates as well, because of the child credit and increases in standard deductions and rate brackets for married couples. Income effects tend to decrease taxable income. Nevertheless, it may be useful to note that the revenue feedback effect with a 0.4 elasticity is 10%. Note also that most of the evidence does not suggest a significant labor supply response. In the working paper version of his study, Feldstein essentially found no effect on labor income. Saez and Gruber find an elasticity of 0.12 for total income, but 0.4 for taxable income, suggesting that labor supply would have a much smaller feedback effect: at an elasticity of 0.12, the feedback arising from an overall income increase would be only 3%. This feedback effect is similar to the lower elasticity measures from the Treasury study. Although this taxable income methodology has some advantages, it is also fraught with a variety of difficulties and with a number of factors that make it likely elasticities are overstated due to transitory effects. In addition, one of the most serious problems is that each tax revision has a different mix of income and substitution effects. This issue is particularly important with the 2001-2004 tax cut which has many important provisions that affect income without altering marginal tax rates, and should increase taxable income, meaning that feedback effects could be negative. Eventually, when data become available, it might be possible to use this method as another way of assessing the 2001-2004 tax cuts' revenue feedback. The analysis presented above based on currently available data and studies suggests that short term stimulus effects that produce feedback are fleeting and small and are unlikely to have played an important role in the recent increase in revenues. The permanent revenue feedback effect for the 2001-2004 tax cuts is also likely to be relatively small, no more than 10%, and the magnitude is not entirely clear. In any case these effects are increasingly offset by the effects of the accumulating debt. In the case of effects on the deficit, these offsetting effects probably occur within the first few years, and thereafter, the accumulation of debt and interest payments adds increasingly to the deficit beyond the conventional revenue costs. The studies and information presented in this report suggest that, at this time, there is not convincing evidence that the positive revenue feedback from the 2001-2004 tax cuts have been of sufficient scale to fully offset their cost to the Treasury. This first part of this section explains how to derive a revenue feedback effect from a taxable income elasticity. The second part provides more details about problems with methodologies, particularly in the early estimates of taxable income elasticity. Measuring the Revenue Offset To determine the revenue offset from using a taxable income elasticity, begin with the equation: (1) R = t times Y(1-t) where R is revenue, t is the tax rate, and Y is taxable income that is a function of the after tax share, (1-t). Totally differentiate equation (1) with respect to t to obtain: (2) dR = Y dt - dt times dY/d(1-t) Define the taxable income elasticity, E, as dY/d(1-t) times (1-t)/Y. Substituting into equation (2), obtain: (3) dR = Ydt(1-Et/(1-t)) Since the revenue change with no feed back is Ydt, the feedback share is Et/(1-t). Technical and Methodological Problems with Early Taxable Elasticity Estimates The basic method of estimating the taxable income elasticity was to compare taxpayers with different changes after tax share (1 minus the tax rate) and examine how their changes in taxable income related. Thus, if an individual with a large percentage increase in after tax share had a larger percentage increase in taxable income, that would be evidence of a response. The first estimates of taxable income elasticity were by Lindsey, Feldstein, and Auten and Carroll; all of these estimates tended to be relatively high. Lindsey examined the 1981 tax cut and obtained an elasticity of 1.6 to 1.8. Feldstein examined the 1986 tax reform and found elasticities of 1.04 to 3.05, and Auten and Carroll, also examining the 1986 reform, obtained estimates similar to Feldstein's. Navratil presented some important critiques of these two studies. First, the Lindsey study did not actually have panel data, so that the same person could be followed over time, and people thus shifted across groups. Navratil was able to obtain panel data and estimated an elasticity of 0.8. Navratil also has a more general critique of these studies, reflecting problems with exogenous income shifts (the increasing inequality of income) and with the assumption that the elasticities are the same across income classes. He illustrates with an example from Feldstein's study where he obtains the estimate of 1.04. To derive the estimating equation consider the two equations for the high group and the low group. In this section of the appendix, y refers to the average percentage change in taxable income of a group and (1-t) refers to the average percentage change in after-tax share of that group. The subscript h refers to high and l to low. (4) y h = a h +b h (1-t h ) (5) y l = a l + b l (1-t l ) where a is a term that captures all of the change outside the tax share variable, and b is the elasticity. The methodology of these studies is called difference in differences and it assumes that a h = a l and b h = b l . In that case, by subtracting (5) from (4) you obtain an estimate of b: (6) b = (y h -y l )/((1-t h )-(1-t l )) In Feldstein's data that yielded the 1.04 estimate, the percentage change in taxable income of the high group was 20.3% and the percentage change in after tax share was 25.6%. For the low group, the percentage change in taxable income was 6.4% and the percentage change in after tax share was 12.2%. Thus b would be calculated as (.203-.064)/(.256-.122) which is 1.04. The peculiar aspect of this change is that the percentage change in taxable income divided by the percentage change in after tax share in each case is smaller than this elasticity—0.79 for the high group and 0.52 for the low group. This implies that the value of a is negative—and, in fact, a negative 6.3%. If interpreted literally, it means that the taxable income would have declined by this amount if no tax changes had occurred. Since income normally grows this is an unreasonable expectation. The more likely explanation is that the a's are different for the two groups or that the b's are different. There is reason to expect the a's to be larger for the high income group because of the trend in inequality of income that had been going on for some time. Navratil re-estimated allowing different values for different income groups, and comparing each group in different time periods; he obtains elasticities that are much smaller than Feldstein's, ranging from 0.11 for the lowest group to 1.09 for the highest. He suggests these estimates are still probably too high because of other factors, including shifting of income across time. A CBO study reviews the remaining studies which have attempted to counter some of the difficulties in the earlier studies, and while the author notes that most of these studies tend to be around 0.4, he also suggests that because of the many methodological issues remaining, any numbers should be used with caution. Among the problems are the exogenous income changes mentioned above which cannot be entirely controlled for, mean reversion (when incomes fluctuate, high-income taxpayers are more likely to have incomes decline and low income ones are more likely to have incomes rise), the possibility of shifting across time or business form to avoid taxes (which means the estimates may be measuring transitory rather than permanent responses), endogeneity of the tax rate, and the problem of controlling for all tax changes. The transitory effects can be quite significant for high-income individuals who can more easily time income source such as bonuses and deductions such as charitable contributions to have low taxable income when tax rates are high. An example of shifting across income sources and contemporaneous tax policy changes was the shift in income from corporate source to Subchapter S income, which may have been affected by both the changes in relative tax rates, and the increase in the number of shareholders allowed for S corporations. Summary: An unexpected increase in revenues has led to a renewed discussion of the effect of the 2001-2004 tax cuts on the economy and the possible feedback effects on revenue. Some proponents of the tax cuts suggest that induced economic growth was large enough that taxes on the additional income more than offset the cost of the tax cuts, causing an increase rather than a decrease in revenues. Other observers doubt that economic growth was related to the tax cuts, or that it was large enough to significantly offset the cost of the cuts. This report reviews available economic studies, theory, and empirical data to assess the possible revenue feedback from the 2001-2004 tax cuts at this time. Four sources of feedback are examined: short-run demand-side stimulus effects, supply-side effects on labor supply and savings, shifting of income from non-taxable to taxable form, and debt service effects. Of the potential sources of feedback, none appears very large relative to the direct revenue cost, and offsetting effects suggest that the effects of the tax cut on the deficit will be to magnify the direct cost rather than reduce it. One source of effect is the short-run stimulus; this effect is temporary, and appears likely to be small, resulting at the peak (about a year and a half following adoption) of no more than a 14% feedback. At the same time, the effect of the deficit in crowding out private capital reduces tax revenues. The debt also adds to the deficit directly through debt service, which can increase the cost of a tax by as much as 25% over the first 10 years, and by larger amounts as time goes on. Conventional supply-side effects arising from increased work and savings are unlikely to have feedbacks of over 10%, and there is some reason to believe that the short-run feedback effect is no more than 3%. There are also some potential feedback effects from shifting into taxable income forms and reducing avoidance, but adding these effects to the conventional supply-side effects still produces a feedback effect in the neighborhood of 10%. Moreover, some of these effects are already incorporated into conventional revenue estimates and they may be overstated for other reasons. Given the positive and negative effects, it is likely that the feedback effect in the very short run would be positive, but at the current time as the stimulus effects have faded and the effect of added debt service has grown, the 2001-2004 tax cuts are probably costing more than their estimated revenue cost. This report will not be updated.
{ "task_name": "govreport_summarization" }
#!/usr/bin/env python3 # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit test for gen_dockerfile.py""" import argparse import filecmp import os import shutil import subprocess import unittest.mock import pytest import yaml import gen_dockerfile # Expected list of files generated EXPECTED_OUTPUT_FILES = set(('Dockerfile', '.dockerignore')) @pytest.fixture def testdata_dir(): testdata_dir = os.path.join(os.path.dirname(__file__), 'testdata') assert os.path.isdir(testdata_dir), ( 'Could not run test: testdata directory not found') return testdata_dir def compare_file(filename, dir1, dir2): """Compare identically named files in two different directories""" assert filecmp.cmp( os.path.join(dir1, filename), os.path.join(dir2, filename)) @pytest.mark.parametrize('app_yaml, expected', [ # Basic app.yaml ('env: flex', { 'base_image': 'some_image_name', 'dockerfile_python_version': '', 'has_requirements_txt': False, 'entrypoint': '', 'is_python_compat': False, }), ('env: flex\nruntime: python-compat', { 'base_image': None, 'dockerfile_python_version': None, 'has_requirements_txt': None, 'entrypoint': None, 'is_python_compat': True, }), # All supported python versions ('runtime_config:\n python_version:', { 'dockerfile_python_version': '', }), ('runtime_config:\n python_version: 2', { 'dockerfile_python_version': '', }), ('runtime_config:\n python_version: 3', { 'dockerfile_python_version': '3.6', }), ('runtime_config:\n python_version: 3.4', { 'dockerfile_python_version': '3.4', }), ('runtime_config:\n python_version: 3.5', { 'dockerfile_python_version': '3.5', }), ('runtime_config:\n python_version: 3.6', { 'dockerfile_python_version': '3.6', }), ('runtime_config:\n python_version: 3.7', { 'dockerfile_python_version': '3.7', }), # entrypoint present ('entrypoint: my entrypoint', { 'entrypoint': 'exec my entrypoint', }), ]) def test_get_app_config_valid(app_yaml, expected): config_file = 'some_config_file' base_image = 'some_image_name' source_dir = 'some_source_dir' raw_app_config = yaml.safe_load(app_yaml) actual = gen_dockerfile.get_app_config( raw_app_config, base_image, config_file, source_dir) for key, value in expected.items(): assert getattr(actual, key) == value def test_get_app_config_requirements_txt(): """requirements.txt file present""" app_yaml = 'env: flex' expected = { 'has_requirements_txt': True, } with unittest.mock.patch.object(os.path, 'isfile', return_value=True): test_get_app_config_valid(app_yaml, expected) @pytest.mark.parametrize('app_yaml', [ # Empty app.yaml '', # Invalid entrypoint 'entrypoint: "bad \\n entrypoint"', # Invalid python version 'runtime_config:\n python_version: 1', 'runtime_config:\n python_version: python2', ]) def test_get_app_config_invalid(app_yaml): config_file = 'some_config_file' base_image = 'some_image_name' source_dir = 'some_source_dir' raw_app_config = yaml.safe_load(app_yaml) with pytest.raises(ValueError): gen_dockerfile.get_app_config( raw_app_config, base_image, config_file, source_dir) # Basic AppConfig used below _BASE_APP_CONFIG = gen_dockerfile.AppConfig( base_image='', dockerfile_python_version='', entrypoint='', has_requirements_txt=False, is_python_compat=False, ) @pytest.mark.parametrize('app_config, should_find, test_string', [ # Requirements.txt (_BASE_APP_CONFIG, False, 'ADD requirements.txt'), (_BASE_APP_CONFIG._replace(has_requirements_txt=True), True, 'ADD requirements.txt'), # Entrypoint (_BASE_APP_CONFIG, False, 'CMD'), (_BASE_APP_CONFIG._replace(entrypoint='my entrypoint'), True, 'CMD my entrypoint'), (_BASE_APP_CONFIG._replace(entrypoint='exec my entrypoint'), True, 'CMD exec my entrypoint'), # Base runtime image (_BASE_APP_CONFIG._replace(base_image='my_base_runtime_image'), True, 'FROM my_base_runtime_image'), # Python version (_BASE_APP_CONFIG._replace(dockerfile_python_version='_my_version'), True, 'python_version=python_my_version'), # python-compat runtime (_BASE_APP_CONFIG._replace(is_python_compat=True), True, 'FROM gcr.io/google_appengine/python-compat-multicore'), ]) def test_generate_files(app_config, should_find, test_string): result = gen_dockerfile.generate_files(app_config) assert set(result.keys()) == EXPECTED_OUTPUT_FILES dockerfile = result['Dockerfile'] if should_find: assert test_string in dockerfile else: assert test_string not in dockerfile def compare_against_golden_files(app, config_dir, testdata_dir): golden_dir = os.path.join(testdata_dir, app + '_golden') for filename in EXPECTED_OUTPUT_FILES: compare_file(filename, config_dir, golden_dir) @pytest.mark.parametrize('app', [ # Sampled from https://github.com/GoogleCloudPlatform/python-docs-samples 'hello_world', # From an internal source. 'hello_world_compat']) def test_generate_dockerfile_command(tmpdir, testdata_dir, app): """Generates output and compares against a set of golden files.""" app_dir = os.path.join(testdata_dir, app) # Copy sample app to writable temp dir, and generate Dockerfile. config_dir = os.path.join(str(tmpdir), 'config') shutil.copytree(app_dir, config_dir) gen_dockerfile.generate_dockerfile_command( base_image='gcr.io/google-appengine/python', config_file=os.path.join(config_dir, 'app.yaml'), source_dir=config_dir) compare_against_golden_files(app, config_dir, testdata_dir) @pytest.mark.parametrize('app', [ # Sampled from https://github.com/GoogleCloudPlatform/python-docs-samples 'hello_world', # From an internal source. 'hello_world_compat']) @pytest.mark.xfail(not shutil.which('gcloud'), reason='Google Cloud SDK is not installed') def test_generate_dockerfile_golden(tmpdir, testdata_dir, app): """Validate our golden files against gcloud app gen-config""" app_dir = os.path.join(testdata_dir, app) # Copy sample app to writable temp dir, and generate Dockerfile. gen_config_dir = os.path.join(str(tmpdir), 'gen_config') shutil.copytree(app_dir, gen_config_dir) app_yaml = os.path.join(gen_config_dir, 'app.yaml') gcloud_args = [ 'gcloud', '--quiet', 'beta', 'app', 'gen-config', gen_config_dir, '--custom', '--config={}'.format(app_yaml) ] print('Invoking gcloud as {}'.format(gcloud_args)) subprocess.check_call(gcloud_args) compare_against_golden_files(app, gen_config_dir, testdata_dir) @pytest.mark.parametrize('argv', [ [], ['argv0', '--base-image=nocolon'], ['argv0', '--base-image=name:andcolon'], ['argv0', '--base-image=name@sha256:digest'], ]) def test_parse_args_valid(argv): args = gen_dockerfile.parse_args(argv) assert args is not None @pytest.mark.parametrize('argv', [ ['argv0', '--base-image='], ['argv0', '--base-image=:'], ['argv0', '--base-image=:noname'], ]) def test_parse_args_invalid(argv): def mock_error(*args): """Prevent argparse from calling sys.exit()""" raise AssertionError(*args) error_patch = unittest.mock.patch.object( argparse.ArgumentParser, 'error', mock_error) with error_patch: with pytest.raises(AssertionError): gen_dockerfile.parse_args(argv) @pytest.mark.parametrize('argv, env, expected', [ # Explicit flag wins (['argv0', '--config=flag/path'], 'env/path', 'flag/path'), (['argv0', '--config=flag/path'], '', 'flag/path'), (['argv0', '--config=flag/path'], None, 'flag/path'), # Otherwise env var wins (['argv0'], 'env/path', 'env/path'), # Otherwise use default name (['argv0'], '', 'app.yaml'), (['argv0'], None, 'app.yaml'), ]) def test_parse_args_config(argv, env, expected): if env is None: mock_environ = {} else: mock_environ = {gen_dockerfile.GAE_APPLICATION_YAML_PATH: env} with unittest.mock.patch.dict('os.environ', mock_environ, clear=True): args = gen_dockerfile.parse_args(argv) assert args.config == expected if __name__ == '__main__': pytest.main([__file__])
{ "task_name": "lcc" }
Passage 1: Mundaka Upanishad The Mundaka Upanishad (Sanskrit: मुण्डक उपनिषद् , Muṇḍaka Upaniṣad ) is an ancient Sanskrit Vedic text, embedded inside Atharva Veda. It is a Mukhya (primary) Upanishad, and is listed as number 5 in the Muktika canon of 108 Upanishads of Hinduism. It is among the most widely translated Upanishads. Passage 2: Chandogya Upanishad The Chandogya Upanishad (Sanskrit: छान्दोग्योपनिषद् , IAST: "Chāndogyopaniṣad") is a Sanskrit text embedded in the Chandogya Brahmana of the Sama Veda of Hinduism. It is one of the oldest Upanishads. It lists as number 9 in the Muktika canon of 108 Upanishads. Passage 3: Maitrayaniya Upanishad The Maitrayaniya Upanishad (Sanskrit: मैत्रायणीय उपनिषद् , Maitrāyaṇīya Upaniṣad ) is an ancient Sanskrit text that is embedded inside the Yajurveda. It is also known as the Maitri Upanishad (Sanskrit: मैत्री उपनिषद् , Maitrī Upaniṣad ), and is listed as number 24 in the Muktika canon of 108 Upanishads. Passage 4: Prashna Upanishad The Prashna Upanishad (Sanskrit: प्रश्न उपनिषद् , Praśna Upaniṣad ) is an ancient Sanskrit text, embedded inside Atharva Veda, ascribed to "Pippalada" sakha of Vedic scholars. It is a Mukhya (primary) Upanishad, and is listed as number 4 in the Muktika canon of 108 Upanishads of Hinduism. Passage 5: Kaushitaki Upanishad The Kaushitaki Upanishad (Sanskrit: कौषीतकि उपनिषद् , Kauṣītaki Upaniṣad ) is an ancient Sanskrit text contained inside the Rigveda. It is associated with the "Kaushitaki" shakha, but a Sāmānya Upanishad, meaning that it is "common" to all schools of Vedanta. It was included in Robert Hume's list of 13 Principal Upanishads, and lists as number 25 in the Muktika canon of 108 Upanishads. Passage 6: Shvetashvatara Upanishad The Shvetashvatara Upanishad (Sanskrit:श्वेताश्वतरोपनिशद or श्वेताश्वतर उपनिषद् IAST "Śvetāśvataropaniṣad ") is an ancient Sanskrit text embedded in the Yajurveda. It is listed as number 14 in the Muktika canon of 108 Upanishads. The Upanishad contains 113 mantras or verses in six chapters. Passage 7: Brihadratha Ikshvaku Brihadratha, belonging to the Ikshvaku race, was a king of the Vedic era (there are several kings of this name in Hindu tradition). This name Brihadratha of a warrior king who was a Maharatha is found in the Rig Veda. The word, Brihadratha, means the Mighty Warrior. He appears at the beginning of the Maitri Upanishad after he had renounced his kingdom in favour of his son, seeking for himself relief from the endless cycle of birth and rebirth. No other information about him or his period is available in this text or in any other text. Maitri Upanishad belongs to the Maitrayaniya branch of Krishna Yajur Veda, which upanishad was taught to Sakayana by Maitri or Maitreya, the son of Mitra. Brihadratha chose the knowledge of the Self when he was offered a boon. He gave up his home and possessions and thereafter assisted by Sakayanya even renounced the “I-ness” of his body. Passage 8: Mantrika Upanishad The Mantrika Upanishad (Sanskrit: मन्त्रिक उपनिषत् , IAST:Māntrika Upaniṣad) is a minor Upanishad of Hinduism. The Sanskrit text is one of the 22 Samanya Upanishads, is part of the Vedanta and Yoga schools of Hindu philosophy literature, and is one of 19 Upanishads attached to the Shukla Yajurveda. In the Muktika canon, narrated by Rama to Hanuman, it is listed at number 32 in the anthology of 108 Upanishads. Passage 9: Yoga-kundalini Upanishad The Yoga-kundalini Upanishad (Sanskrit: योगकुण्डलिनी उपनिषत् IAST: Yogakuṇḍalini Upaniṣad ), also called Yogakundali Upanishad (Sanskrit: योगकुण्डल्युपनिषत्, IAST: Yogakuṇḍalī Upaniṣad), is a minor Upanishad of Hinduism. The Sanskrit text is one of the 20 Yoga Upanishads, and is one of 32 Upanishads attached to the Krishna Yajurveda. In the Muktika canon, narrated by Rama to Hanuman, it is listed at number 86 in the anthology of 108 Upanishads. Passage 10: Pranagnihotra Upanishad The Pranagnihotra Upanishad (Sanskrit: प्राणाग्निहोत्र उपनिषत् , IAST:Pranagnihotra Upaniṣad) is a minor Upanishad of Hinduism. In the anthology of 108 Upanishads of the Muktika canon, narrated by Rama to Hanuman, it is listed at number 94. The Sanskrit text is one of the 22 Samanya Upanishads, part of the Vedanta school of Hindu philosophy literature and is attached to the Atharva Veda. The Upanishad comprises 23 verses. Question: Brihadratha Ikshvaku appears at the beginning of a Sanskrit text that is listed as what number in the Muktika canon? Answer: 24
{ "task_name": "hotpotqa" }
Passage 1: Civil Rights Act of 1968 The Civil Rights Act of 1968, (Pub.L. 90–284 , 82 Stat. 73 , enacted  11, 1968 ), also known as the Fair Housing Act, is a landmark part of legislation in the United States that provided for equal housing opportunities regardless of race, religion, or national origin and made it a federal crime to “by force or by threat of force, injure, intimidate, or interfere with anyone … by reason of their race, color, religion, or national origin.” The Act was signed into law during the King assassination riots by President Lyndon B. Johnson, who had previously signed the Civil Rights Act and Voting Rights Act into law. Passage 2: Executive Order 11246 Executive Order 11246, signed by President Lyndon B. Johnson on September 24, 1965, established requirements for non-discriminatory practices in hiring and employment on the part of U.S. government contractors. It "prohibits federal contractors and federally assisted construction contractors and subcontractors, who do over $10,000 in Government business in one year from discriminating in employment decisions on the basis of race, color, religion, sex, or national origin." It also requires contractors to "take affirmative action to ensure that applicants are employed, and that employees are treated during employment, without regard to their race, color, religion, sex or national origin." The phrase "affirmative action" had appeared previously in Executive Order 10925 in 1961. Passage 3: Languages of Romania In Romania there are several spoken languages. Beside Romanian, the only official language nationwide, other spoken languages include Hungarian, English, Lithuanian, Bulgarian, Serbo-Croatian, Russian, Slovak, Romani, Ukrainian, and German. Passage 4: Chung (surname) Chung is a surname whose bearers are generally people of Chinese or Korean descent. It is also a Vietnamese surname worn by people of Chinese descent but is very rare in Vietnam; the surname is known as Zhong in Chinese, Jung (정) in Korean, and exactly Chung in Vietnam. Passage 5: Palumbo Palumbo is a surname of Italian origin, derived from Palombo literally meaning "Ring Dove" or Palombella meaning "Wood Pigeon" in the dialects of southern Italy. The Palumbo family crest depicts a Dove with an olive banch in its beak. Due to this many consider the meaning of Palumbo to be "Dove of Peace". It could refer to: Passage 6: Languages of Italy There are approximately 34 living spoken languages and related dialects in Italy, most of which are indigenous evolutions of Vulgar Latin, and thus are classified as Romance languages. Although they are sometimes referred to as regional languages, there is no uniformity within any Italian region, and speakers from one locale within a region are typically very aware of features that distinguish their local language from the speech of other places nearby. The official and most widely spoken language is Italian, a descendant of Tuscan. Passage 7: Sign language Sign language (also signed language) is a language which chiefly uses manual communication to convey meaning, as opposed to spoken language. This can involve simultaneously combining hand shapes, orientation and movement of the hands, arms or body, and facial expressions to express a speaker's thoughts. Sign languages share many similarities with spoken languages (sometimes called "oral languages"), which depend primarily on sound, and linguists consider both to be types of natural language. Although there are some significant differences between signed and spoken languages, such as how they use space grammatically, sign languages show the same linguistic properties and use the same language faculty as do spoken languages. They should not be confused with body language, which is a kind of non-linguistic communication. Passage 8: Sign language in the brain Sign language refers to a mode of communication, distinct from spoken languages, which uses visual gestures with the hands accompanied by body language to express meaning. It has been determined that the brain's left side is the dominant side utilized for producing and understanding sign language, just as it is for speech. In 1861, Paul Broca studied patients with the ability to understand spoken languages but the inability to produce them. The damaged area was named Broca's area, and located in the left hemisphere’s inferior frontal gyrus (Brodmann areas 44, 45). Soon after, in 1874, Carl Wernicke studied patients with the reverse deficits: patients could produce spoken language, but could not comprehend it. The damaged area was named Wernicke's area, and is located in the left hemisphere’s posterior superior temporal gyrus (Brodmann area 22). Signers with damage in Broca's area, have problems producing signs. Those with damage in the Wernicke's area (left hemisphere) in the temporal lobe of the brain have problems comprehending signed languages. Early on, it was noted that Broca’s area was near the part of the motor cortex controlling the face and mouth. Likewise, Wernicke's area was near the auditory cortex. These motor and auditory areas are important in spoken language processing and production, but the connection to signed languages had yet to be uncovered. For this reason, the left hemisphere was described as the verbal hemisphere, with the right hemisphere deemed to be responsible for spatial tasks. This criteria and classification was used to denounce signed languages as equal with their spoken counterparts before it was more widely agreed upon that due to the similarities in cortical connectivity they are linguistically and cognitively equivalent. In the 1980's research on deaf patients with left hemisphere stroke were examined to explore the brains connection with signed languages. The left perisylvian region was discovered to be functionally critical for language, spoken and signed. Its location near several key auditory processing regions led to the belief that language processing required auditory input and was used to discredit signed languages as "real languages." This research opened the doorway for linguistic analysis and further research of signed languages. Signed languages, like spoken languages, are highly structured linguistic system; they have their own sets of phonological, morphological and syntactic characteristics. Despite complex differences between spoken and signed languages, the associated brain areas are thus far thought to share a lot in common. Passage 9: Canaanite languages The Canaanite languages or Canaanite dialects are one of the four subdivisions of the Northwest Semitic languages, the others being the Aramaic language, the Ugaritic language, and the Amorite language. They were spoken by the ancient Semitic people of the Canaan and Levant regions, an area encompassing what are today Israel, Jordan, Sinai, Lebanon, Syria, the Palestinian territories, and also some fringe areas of southern Turkey and the northern Arabian peninsula. The Canaanites are broadly defined to include the Israelites (including Judeans and Samaritans), Phoenicians (including Carthaginians), Amorites, Ammonites, Moabites, Edomites, Suteans, Ekronites and Amalekites. The Canaanite languages had ceased to be everyday spoken languages by the 1st millennium AD, but Hebrew remained in continuous use by many Jews since that period into medieval times as a liturgical language, literary language, and for commerce, until it was revived as an everyday spoken language in the late 19th and early 20th centuries, and became the main language of the Jews of Palestine and later the State of Israel. Hebrew is the only living Canaanite language today. Passage 10: Dramatic Prakrit Dramatic Prakrits were those standard forms of Prakrit dialects that were used in dramas and other literature in medieval India. They may have once been spoken languages or were based on spoken languages, but continued to be used as literary languages long after they ceased to be spoken. Dramatic Prakrits are important for the study of the development of Indo-Aryan languages, because their usage plays and literature is always accompanied by a translation in Sanskrit. Question: Palumbo is a surname whose national origin has approximately how many living spoken languages? Answer: 34
{ "task_name": "hotpotqa" }
Passage 1: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 2: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 3: Neal Israel Neal Israel (born July 27, 1945) is an American actor, screenwriter, film and television producer and director best known for his comedic work in the 1980s for films such as "Police AcademyReal Genius", and "Bachelor Party". Passage 4: Brian Kennedy (gallery director) Brian Patrick Kennedy( born 5 November 1961) is an Irish- born art museum director who has worked in Ireland and Australia, and now lives and works in the United States. He is currently the director of the Peabody Essex Museum. He was the director of the Toledo Museum of Art in Ohio from 2010 to 2019. He was the director of the Hood Museum of Art from 2005 to 2010, and the National Gallery of Australia( Canberra) from 1997- 2004. Passage 5: John Donatich John Donatich is the Director of Yale University Press. Passage 6: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Passage 7: Tunnel Vision (1976 film) TunnelVision (also known as Tunnel Vision) is a satirical 1976 comedy anthology film featuring Roger Bowen, Chevy Chase, John Candy, Howard Hesseman, Joe Flaherty, Laraine Newman, Betty Thomas, Phil Proctor, Al Franken, Ron Silver, Tom Davis, and Michael Overly, with appearances by voiceover artists Ernie Anderson and Danny Dark. It was directed by Neal Israel and Bradley R. Swirnoff and produced by Joe Roth. Although the title is repeatedly displayed in the film as being spelled "Tunnelvision," it is frequently identified as "Tunnel Vision" in home video reissues Passage 8: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 9: John Farrell (businessman) John Farrell is the director of YouTube in Latin America. Passage 10: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Question: What nationality is the director of film Tunnel Vision (1976 Film)? Answer: American
{ "task_name": "2WikiMultihopQA" }
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """LSTM Block Cell ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from tensorflow.contrib.rnn.ops import gen_lstm_ops from tensorflow.contrib.rnn.python.ops import fused_rnn_cell from tensorflow.contrib.util import loader from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import variable_scope as vs from tensorflow.python.platform import resource_loader _lstm_ops_so = loader.load_op_library( resource_loader.get_path_to_datafile("_lstm_ops.so")) # pylint: disable=invalid-name def _lstm_block_cell(x, cs_prev, h_prev, w, b, wci=None, wcf=None, wco=None, forget_bias=None, cell_clip=None, use_peephole=None, name=None): r"""Computes the LSTM cell forward propagation for 1 time step. This implementation uses 1 weight matrix and 1 bias vector, and there's an optional peephole connection. This kernel op implements the following mathematical equations: ```python xh = [x, h_prev] [i, ci, f, o] = xh * w + b f = f + forget_bias if not use_peephole: wci = wcf = wco = 0 i = sigmoid(cs_prev * wci + i) f = sigmoid(cs_prev * wcf + f) ci = tanh(ci) cs = ci .* i + cs_prev .* f cs = clip(cs, cell_clip) o = sigmoid(cs * wco + o) co = tanh(cs) h = co .* o ``` Args: x: A `Tensor`. Must be one of the following types: `float32`. The input to the LSTM cell, shape (batch_size, num_inputs). cs_prev: A `Tensor`. Must have the same type as `x`. Value of the cell state at previous time step. h_prev: A `Tensor`. Must have the same type as `x`. Output of the previous cell at previous time step. w: A `Tensor`. Must have the same type as `x`. The weight matrix. b: A `Tensor`. Must have the same type as `x`. The bias vector. wci: A `Tensor`. Must have the same type as `x`. The weight matrix for input gate peephole connection. wcf: A `Tensor`. Must have the same type as `x`. The weight matrix for forget gate peephole connection. wco: A `Tensor`. Must have the same type as `x`. The weight matrix for output gate peephole connection. forget_bias: An optional `float`. Defaults to `1`. The forget gate bias. cell_clip: An optional `float`. Defaults to `3`. Value to clip the 'cs' value to. Disable by setting to negative value. use_peephole: An optional `bool`. Defaults to `False`. Whether to use peephole weights. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (i, cs, f, o, ci, co, h). i: A `Tensor`. Has the same type as `x`. The input gate. cs: A `Tensor`. Has the same type as `x`. The cell state before the tanh. f: A `Tensor`. Has the same type as `x`. The forget gate. o: A `Tensor`. Has the same type as `x`. The output gate. ci: A `Tensor`. Has the same type as `x`. The cell input. co: A `Tensor`. Has the same type as `x`. The cell after the tanh. h: A `Tensor`. Has the same type as `x`. The output h vector. Raises: ValueError: If cell_size is None. """ if wci is None: cell_size = cs_prev.get_shape().with_rank(2)[1].value if cell_size is None: raise ValueError("cell_size from `cs_prev` should not be None.") wci = array_ops.constant(0, dtype=dtypes.float32, shape=[cell_size]) wco = wci wcf = wci # pylint: disable=protected-access return gen_lstm_ops.lstm_block_cell( x=x, cs_prev=cs_prev, h_prev=h_prev, w=w, wci=wci, wco=wco, wcf=wcf, b=b, forget_bias=forget_bias, cell_clip=cell_clip, use_peephole=use_peephole, name=name) # pylint: enable=protected-access def _block_lstm(seq_len_max, x, w, b, cs_prev=None, h_prev=None, wci=None, wcf=None, wco=None, forget_bias=None, cell_clip=None, use_peephole=None, name=None): r"""TODO(williamchan): add doc. Args: seq_len_max: A `Tensor` of type `int64`. x: A list of at least 1 `Tensor` objects of the same type in: `float32`. w: A `Tensor`. Must have the same type as `x`. b: A `Tensor`. Must have the same type as `x`. cs_prev: A `Tensor`. Must have the same type as `x`. h_prev: A `Tensor`. Must have the same type as `x`. wci: A `Tensor`. Must have the same type as `x`. wcf: A `Tensor`. Must have the same type as `x`. wco: A `Tensor`. Must have the same type as `x`. forget_bias: An optional `float`. Defaults to `1`. cell_clip: An optional `float`. Defaults to `3`. use_peephole: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (i, cs, f, o, ci, co, h). i: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. cs: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. f: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. o: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. ci: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. co: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. h: A list with the same number of `Tensor` objects as `x` of `Tensor` objects of the same type as x. Raises: ValueError: If `b` does not have a valid shape. """ batch_size = x[0].get_shape().with_rank(2)[0].value cell_size4 = b.get_shape().with_rank(1)[0].value if cell_size4 is None: raise ValueError("`b` shape must not be None.") cell_size = cell_size4 / 4 zero_state = None if cs_prev is None or h_prev is None: zero_state = array_ops.constant( 0, dtype=dtypes.float32, shape=[batch_size, cell_size]) if cs_prev is None: cs_prev = zero_state if h_prev is None: h_prev = zero_state if wci is None: wci = array_ops.constant(0, dtype=dtypes.float32, shape=[cell_size]) wco = wci wcf = wci # pylint: disable=protected-access i, cs, f, o, ci, co, h = gen_lstm_ops.block_lstm( seq_len_max=seq_len_max, x=array_ops.stack(x), cs_prev=cs_prev, h_prev=h_prev, w=w, wci=wci, wco=wco, wcf=wcf, b=b, forget_bias=forget_bias, cell_clip=cell_clip, name=name, use_peephole=use_peephole) return array_ops.unstack(i), array_ops.unstack(cs), array_ops.unstack( f), array_ops.unstack(o), array_ops.unstack(ci), array_ops.unstack( co), array_ops.unstack(h) # pylint: enable=protected-access # pylint: enable=invalid-name _lstm_block_cell_grad_outputs = ["cs_prev_grad", "dicfo"] @ops.RegisterGradient("LSTMBlockCell") def _LSTMBlockCellGrad(op, *grad): """Gradient for LSTMBlockCell.""" (x, cs_prev, h_prev, w, wci, wco, wcf, b) = op.inputs (i, cs, f, o, ci, co, _) = op.outputs (_, cs_grad, _, _, _, _, h_grad) = grad batch_size = x.get_shape().with_rank(2)[0].value if batch_size is None: batch_size = -1 input_size = x.get_shape().with_rank(2)[1].value if input_size is None: raise ValueError("input_size from `x` should not be None.") cell_size = cs_prev.get_shape().with_rank(2)[1].value if cell_size is None: raise ValueError("cell_size from `cs_prev` should not be None.") (cs_prev_grad, dicfo, wci_grad, wcf_grad, wco_grad) = gen_lstm_ops.lstm_block_cell_grad( x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, cs_grad, h_grad, use_peephole=op.get_attr("use_peephole")) # Backprop from dicfo to xh. xh_grad = math_ops.matmul(dicfo, w, transpose_b=True) x_grad = array_ops.slice(xh_grad, (0, 0), (batch_size, input_size)) x_grad.get_shape().merge_with(x.get_shape()) h_prev_grad = array_ops.slice(xh_grad, (0, input_size), (batch_size, cell_size)) h_prev_grad.get_shape().merge_with(h_prev.get_shape()) # Backprop from dicfo to w. xh = array_ops.concat([x, h_prev], 1) w_grad = math_ops.matmul(xh, dicfo, transpose_a=True) w_grad.get_shape().merge_with(w.get_shape()) # Backprop from dicfo to b. b_grad = nn_ops.bias_add_grad(dicfo) b_grad.get_shape().merge_with(b.get_shape()) return (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad) @ops.RegisterGradient("BlockLSTM") def _BlockLSTMGrad(op, *grad): """Gradient for BlockLSTM.""" seq_len_max, x, cs_prev, h_prev, w, wci, wco, wcf, b = op.inputs i, cs, f, o, ci, co, h = op.outputs cs_grad = grad[1] h_grad = grad[6] (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wco_grad, wcf_grad, b_grad) = gen_lstm_ops.block_lstm_grad( seq_len_max, x, cs_prev, h_prev, w, wci, wco, wcf, b, i, cs, f, o, ci, co, h, cs_grad, h_grad, use_peephole=op.get_attr("use_peephole")) return [None, x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wco_grad, wcf_grad, b_grad] class LSTMBlockCell(rnn_cell_impl.RNNCell): """Basic LSTM recurrent network cell. The implementation is based on: http://arxiv.org/abs/1409.2329. We add `forget_bias` (default: 1) to the biases of the forget gate in order to reduce the scale of forgetting in the beginning of the training. Unlike `rnn_cell_impl.LSTMCell`, this is a monolithic op and should be much faster. The weight and bias matrices should be compatible as long as the variable scope matches. """ def __init__(self, num_units, forget_bias=1.0, clip_cell=True, use_peephole=False, reuse=None): """Initialize the basic LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). clip_cell: boolean, whether to apply cell clipping. See `_lstm_block_cell()` for details. use_peephole: Whether to use peephole connections or not. reuse: (optional) boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. When restoring from CudnnLSTM-trained checkpoints, must use CudnnCompatibleLSTMBlockCell instead. """ super(LSTMBlockCell, self).__init__(_reuse=reuse) self._num_units = num_units self._forget_bias = forget_bias self._use_peephole = use_peephole self._clip_cell = clip_cell self._names = { "W": "kernel", "b": "bias", "wci": "w_i_diag", "wco": "w_o_diag", "wcf": "w_f_diag", "scope": "lstm_cell" } @property def state_size(self): return rnn_cell_impl.LSTMStateTuple(self._num_units, self._num_units) @property def output_size(self): return self._num_units def __call__(self, x, states_prev, scope=None): """Long short-term memory cell (LSTM).""" with vs.variable_scope(scope or self._names["scope"]): x_shape = x.get_shape().with_rank(2) if not x_shape[1].value: raise ValueError("Expecting x_shape[1] to be set: %s" % str(x_shape)) if len(states_prev) != 2: raise ValueError("Expecting states_prev to be a tuple with length 2.") input_size = x_shape[1].value w = vs.get_variable(self._names["W"], [input_size + self._num_units, self._num_units * 4]) b = vs.get_variable( self._names["b"], [w.get_shape().with_rank(2)[1].value], initializer=init_ops.constant_initializer(0.0)) if self._use_peephole: wci = vs.get_variable(self._names["wci"], [self._num_units]) wco = vs.get_variable(self._names["wco"], [self._num_units]) wcf = vs.get_variable(self._names["wcf"], [self._num_units]) else: wci = wco = wcf = array_ops.zeros([self._num_units]) (cs_prev, h_prev) = states_prev (_, cs, _, _, _, _, h) = _lstm_block_cell( x, cs_prev, h_prev, w, b, wci=wci, wco=wco, wcf=wcf, forget_bias=self._forget_bias, cell_clip=None if self._clip_cell else -1, use_peephole=self._use_peephole) new_state = rnn_cell_impl.LSTMStateTuple(cs, h) return h, new_state class LSTMBlockWrapper(fused_rnn_cell.FusedRNNCell): """This is a helper class that provides housekeeping for LSTM cells. This may be useful for alternative LSTM and similar type of cells. The subclasses must implement `_call_cell` method and `num_units` property. """ @abc.abstractproperty def num_units(self): """Number of units in this cell (output dimension).""" pass @abc.abstractmethod def _call_cell(self, inputs, initial_cell_state, initial_output, dtype, sequence_length): """Run this LSTM on inputs, starting from the given state. This method must be implemented by subclasses and does the actual work of calling the cell. Args: inputs: `3-D` tensor with shape `[time_len, batch_size, input_size]` initial_cell_state: initial value for cell state, shape `[batch_size, self._num_units]` initial_output: initial value of cell output, shape `[batch_size, self._num_units]` dtype: The data type for the initial state and expected output. sequence_length: Specifies the length of each sequence in inputs. An int32 or int64 vector (tensor) size [batch_size], values in [0, time_len) or None. Returns: A pair containing: - State: A `3-D` tensor of shape `[time_len, batch_size, output_size]` - Output: A `3-D` tensor of shape `[time_len, batch_size, output_size]` """ pass def __call__(self, inputs, initial_state=None, dtype=None, sequence_length=None, scope=None): """Run this LSTM on inputs, starting from the given state. Args: inputs: `3-D` tensor with shape `[time_len, batch_size, input_size]` or a list of `time_len` tensors of shape `[batch_size, input_size]`. initial_state: a tuple `(initial_cell_state, initial_output)` with tensors of shape `[batch_size, self._num_units]`. If this is not provided, the cell is expected to create a zero initial state of type `dtype`. dtype: The data type for the initial state and expected output. Required if `initial_state` is not provided or RNN state has a heterogeneous dtype. sequence_length: Specifies the length of each sequence in inputs. An `int32` or `int64` vector (tensor) size `[batch_size]`, values in `[0, time_len).` Defaults to `time_len` for each element. scope: `VariableScope` for the created subgraph; defaults to class name. Returns: A pair containing: - Output: A `3-D` tensor of shape `[time_len, batch_size, output_size]` or a list of time_len tensors of shape `[batch_size, output_size]`, to match the type of the `inputs`. - Final state: a tuple `(cell_state, output)` matching `initial_state`. Raises: ValueError: in case of shape mismatches """ with vs.variable_scope(scope or "lstm_block_wrapper"): is_list = isinstance(inputs, list) if is_list: inputs = array_ops.stack(inputs) inputs_shape = inputs.get_shape().with_rank(3) if not inputs_shape[2]: raise ValueError("Expecting inputs_shape[2] to be set: %s" % inputs_shape) batch_size = inputs_shape[1].value if batch_size is None: batch_size = array_ops.shape(inputs)[1] time_len = inputs_shape[0].value if time_len is None: time_len = array_ops.shape(inputs)[0] # Provide default values for initial_state and dtype if initial_state is None: if dtype is None: raise ValueError( "Either initial_state or dtype needs to be specified") z = array_ops.zeros( array_ops.stack([batch_size, self.num_units]), dtype=dtype) initial_state = z, z else: if len(initial_state) != 2: raise ValueError( "Expecting initial_state to be a tuple with length 2 or None") if dtype is None: dtype = initial_state[0].dtype # create the actual cell if sequence_length is not None: sequence_length = ops.convert_to_tensor(sequence_length) initial_cell_state, initial_output = initial_state # pylint: disable=unpacking-non-sequence cell_states, outputs = self._call_cell(inputs, initial_cell_state, initial_output, dtype, sequence_length) if sequence_length is not None: # Mask out the part beyond sequence_length mask = array_ops.transpose( array_ops.sequence_mask( sequence_length, time_len, dtype=dtype), [1, 0]) mask = array_ops.tile( array_ops.expand_dims(mask, [-1]), [1, 1, self.num_units]) outputs *= mask # Prepend initial states to cell_states and outputs for indexing to work # correctly,since we want to access the last valid state at # sequence_length - 1, which can even be -1, corresponding to the # initial state. mod_cell_states = array_ops.concat( [array_ops.expand_dims(initial_cell_state, [0]), cell_states], 0) mod_outputs = array_ops.concat( [array_ops.expand_dims(initial_output, [0]), outputs], 0) final_cell_state = self._gather_states(mod_cell_states, sequence_length, batch_size) final_output = self._gather_states(mod_outputs, sequence_length, batch_size) else: # No sequence_lengths used: final state is the last state final_cell_state = cell_states[-1] final_output = outputs[-1] if is_list: # Input was a list, so return a list outputs = array_ops.unstack(outputs) final_state = rnn_cell_impl.LSTMStateTuple(final_cell_state, final_output) return outputs, final_state def _gather_states(self, data, indices, batch_size): """Produce `out`, s.t. out(i, j) = data(indices(i), i, j).""" mod_indices = indices * batch_size + math_ops.range(batch_size) return array_ops.gather( array_ops.reshape(data, [-1, self.num_units]), mod_indices) class LSTMBlockFusedCell(LSTMBlockWrapper): """FusedRNNCell implementation of LSTM. This is an extremely efficient LSTM implementation, that uses a single TF op for the entire LSTM. It should be both faster and more memory-efficient than LSTMBlockCell defined above. The implementation is based on: http://arxiv.org/abs/1409.2329. We add forget_bias (default: 1) to the biases of the forget gate in order to reduce the scale of forgetting in the beginning of the training. The variable naming is consistent with `rnn_cell_impl.LSTMCell`. """ def __init__(self, num_units, forget_bias=1.0, cell_clip=None, use_peephole=False): """Initialize the LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). cell_clip: clip the cell to this value. Defaults to `3`. use_peephole: Whether to use peephole connections or not. """ self._num_units = num_units self._forget_bias = forget_bias self._cell_clip = cell_clip self._use_peephole = use_peephole @property def num_units(self): """Number of units in this cell (output dimension).""" return self._num_units def _call_cell(self, inputs, initial_cell_state, initial_output, dtype, sequence_length): """Run this LSTM on inputs, starting from the given state. Args: inputs: `3-D` tensor with shape `[time_len, batch_size, input_size]` initial_cell_state: initial value for cell state, shape `[batch_size, self._num_units]` initial_output: initial value of cell output, shape `[batch_size, self._num_units]` dtype: The data type for the initial state and expected output. sequence_length: Specifies the length of each sequence in inputs. An `int32` or `int64` vector (tensor) size `[batch_size]`, values in `[0, time_len)` or None. Returns: A pair containing: - Cell state (cs): A `3-D` tensor of shape `[time_len, batch_size, output_size]` - Output (h): A `3-D` tensor of shape `[time_len, batch_size, output_size]` """ inputs_shape = inputs.get_shape().with_rank(3) time_len = inputs_shape[0].value if time_len is None: time_len = array_ops.shape(inputs)[0] input_size = inputs_shape[2].value w = vs.get_variable( "kernel", [input_size + self._num_units, self._num_units * 4], dtype=dtype) b = vs.get_variable( "bias", [w.get_shape().with_rank(2)[1]], initializer=init_ops.constant_initializer(0.0), dtype=dtype) if self._use_peephole: wci = vs.get_variable("w_i_diag", [self._num_units], dtype=dtype) wco = vs.get_variable("w_o_diag", [self._num_units], dtype=dtype) wcf = vs.get_variable("w_f_diag", [self._num_units], dtype=dtype) else: wci = wco = wcf = array_ops.zeros([self._num_units], dtype=dtype) if sequence_length is None: max_seq_len = math_ops.to_int64(time_len) else: max_seq_len = math_ops.to_int64(math_ops.reduce_max(sequence_length)) _, cs, _, _, _, _, h = gen_lstm_ops.block_lstm( seq_len_max=max_seq_len, x=inputs, cs_prev=initial_cell_state, h_prev=initial_output, w=w, wci=wci, wco=wco, wcf=wcf, b=b, forget_bias=self._forget_bias, cell_clip=self._cell_clip, use_peephole=self._use_peephole) return cs, h
{ "task_name": "lcc" }
Passage 1: Qaleh-ye Bakhtiar Qaleh- ye Bakhtiar or Qaleh- ye Bakhteyar may refer to: Passage 2: Qaleh-ye Zaras Qaleh- ye Zaras( also Romanized as Qal‘eh- ye Zarās, Qal‘eh Zarās, and Qal‘eh Zarrās; also known as Ghal’eh Zaras) is a village in Qaleh- ye Khvajeh Rural District, in the Central District of Andika County, Khuzestan Province, Iran. At the 2006 census, its population was 291, in 49 families. Passage 3: Qaleh-ye Khanjan Qaleh- ye Khanjan( also Romanized as Qal ‘ eh- ye Khānjān; also known as Khānjān Khān, Qal‘eh- ye Khānjān Khān, and Sar Tang -e Eslāmābād) is a village in Gerit Rural District, Papi District, Khorramabad County, Lorestan Province, Iran. At the 2006 census, its population was 119, in 23 families. Passage 4: Qaleh-ye Askar Qaleh- ye Askar or Qaleh Askar, also rendered as Qaleh- ye Asgar and Qaleh Asgar may refer to: Passage 5: Qaleh-ye Pain Qaleh- ye Pain may refer to: Passage 6: Bandar, Yazd Bandar is a village in Rabatat Rural District, Kharanaq District, Ardakan County, Yazd Province, Iran. At the 2006 census, its population was 22, in 8 families. Passage 7: Sar Yazd Saryazd( also Romanized as Sar -e Yazd and Sar- i- Yezd; also known as Mehriz) is a village in Khvormiz Rural District, in the Central District of Mehriz County, Yazd Province, Iran. At the 2006 census, its population was 421, in 141 families .. The village's name means' head of Yazd' in Persian. Passage 8: Hamashahr Hamashahr is a city and capital of Hamaijan District, in Sepidan County, Fars Province, Iran. It was formed in 2010 from an amalgamation of the villages of Deh Bid, Dehpagah, Damqanat, Qaleh- ye Abbasabad, and Qaleh- ye Tiskhani. As of the 2006 census, the city( the combination of the amalgamated villages) had a population of 2,385, in 549 families. Passage 9: Qaleh-ye Nashin Shahi Qaleh- ye Nashin Shahi( also Romanized as Qalʿeh Nashīn Shāhī; also known as Qaleh- ye Shinshahi) is a village in Shurab Rural District, Veysian District, Dowreh County, Lorestan Province, Iran. At the 2006 census, its population was 72, in 14 families. Passage 10: Khosrow, Andika Khosrow is a village in Qaleh- ye Khvajeh Rural District, in the Central District of Andika County, Khuzestan Province, Iran. At the 2006 census, its population was 70, in 13 families. Question: Are Bandar, Yazd and Qaleh-Ye Khanjan both located in the same country? Answer: yes
{ "task_name": "2WikiMultihopQA" }
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Grappler LayoutOptimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf import device_properties_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.core.protobuf import saver_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.grappler import cluster as gcluster from tensorflow.python.grappler import tf_optimizer from tensorflow.python.layers import convolutional as conv_layers from tensorflow.python.ops import array_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import gen_nn_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import random_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent from tensorflow.python.training import saver as saver_lib def _weight(shape): """Generates a weight of a given shape.""" return random_ops.truncated_normal(shape, seed=0, stddev=0.1) def _bias(shape): """Generates a bias of a given shape.""" return constant_op.constant(0.1, shape=shape) def _conv2d(x, w): """Returns a 2d convolution layer with full stride.""" return nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME') def _max_pool_2x2(x): """Downsamples a feature map by 2X.""" return nn.max_pool( x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Taken from tensorflow/examples/tutorials/mnist/mnist_deep.py def _two_layer_model(x): x_image = array_ops.reshape(x, [-1, 28, 28, 1]) w_conv1 = _weight([5, 5, 1, 32]) b_conv1 = _bias([32]) h_conv1 = nn.relu(_conv2d(x_image, w_conv1) + b_conv1) h_pool1 = _max_pool_2x2(h_conv1) w_conv2 = _weight([5, 5, 32, 64]) b_conv2 = _bias([64]) h_conv2 = nn.relu(_conv2d(h_pool1, w_conv2) + b_conv2) h_pool2 = _max_pool_2x2(h_conv2) return h_pool2 def _model_with_second_port(): random_seed.set_random_seed(0) x = random_ops.truncated_normal([2, 5, 5, 4], seed=0) scale = constant_op.constant(0.1, shape=[4]) offset = constant_op.constant(0.3, shape=[4]) y, mean, _ = nn.fused_batch_norm(x, scale, offset) mul = math_ops.add(y, mean) output = array_ops.identity(mul) return output def _model_with_branch(x): x_image = array_ops.reshape(x, [-1, 28, 28, 1]) w_conv1 = _weight([5, 5, 1, 32]) w_conv2 = _weight([5, 5, 1, 32]) c_conv1 = _conv2d(x_image, w_conv1) c_conv2 = _conv2d(x_image, w_conv2) add = math_ops.add(c_conv1, c_conv2) return add def _model_with_vec_and_4d(x): x_image = array_ops.reshape(x, [-1, 28, 28, 1]) w_conv1 = _weight([5, 5, 1, 32]) c_conv1 = _conv2d(x_image, w_conv1) vector = constant_op.constant(6.4, shape=[32]) add = math_ops.add(c_conv1, vector) return add def _loop(): random_seed.set_random_seed(0) x1 = random_ops.truncated_normal([1, 784], seed=0) x2 = random_ops.truncated_normal([1, 784], seed=0) x3 = random_ops.truncated_normal([1, 784], seed=0) x4 = random_ops.truncated_normal([1, 784], seed=0) elems = (x1, x2, x3, x4) outputs = functional_ops.map_fn(_two_layer_model, elems, dtype=dtypes.float32) return outputs def _loop_with_branch(): random_seed.set_random_seed(0) x1 = random_ops.truncated_normal([1, 784], seed=0) x2 = random_ops.truncated_normal([1, 784], seed=0) x3 = random_ops.truncated_normal([1, 784], seed=0) x4 = random_ops.truncated_normal([1, 784], seed=0) elems = (x1, x2, x3, x4) outputs = functional_ops.map_fn( _model_with_branch, elems, dtype=dtypes.float32) return outputs def _loop_with_vec_and_4d(): random_seed.set_random_seed(0) x1 = random_ops.truncated_normal([1, 784], seed=0) x2 = random_ops.truncated_normal([1, 784], seed=0) x3 = random_ops.truncated_normal([1, 784], seed=0) x4 = random_ops.truncated_normal([1, 784], seed=0) elems = (x1, x2, x3, x4) outputs = functional_ops.map_fn( _model_with_vec_and_4d, elems, dtype=dtypes.float32) return outputs def _get_config(layout_optimizer=True): if layout_optimizer: rewrite_options = rewriter_config_pb2.RewriterConfig( layout_optimizer=rewriter_config_pb2.RewriterConfig.ON) else: rewrite_options = rewriter_config_pb2.RewriterConfig( layout_optimizer=rewriter_config_pb2.RewriterConfig.OFF) graph_options = config_pb2.GraphOptions( rewrite_options=rewrite_options, build_cost_model=1) config = config_pb2.ConfigProto(graph_options=graph_options) return config def _simple_metagraph(depthwise=False): random_seed.set_random_seed(0) x = variables.Variable(random_ops.truncated_normal([1, 200, 200, 3], seed=0)) conv = conv_layers.separable_conv2d if depthwise else conv_layers.conv2d y = conv(x, 32, [3, 3]) z = conv(y, 32, [3, 3]) optimizer = gradient_descent.GradientDescentOptimizer(1e-4) loss = math_ops.reduce_mean(z) train_op = optimizer.minimize(loss) graph = ops.get_default_graph() graph.add_to_collection('train_op', train_op) meta_graph = saver_lib.export_meta_graph(graph_def=graph.as_graph_def()) return meta_graph def _get_cluster(): named_device = device_properties_pb2.NamedDevice() named_device.name = '/GPU:0' named_device.properties.type = 'GPU' named_device.properties.environment['architecture'] = '4' cluster = gcluster.Cluster(devices=[named_device]) return cluster class LayoutOptimizerTest(test.TestCase): """Tests the Grappler layout optimizer.""" def _train(self, checkpoint_path, layout_optimizer=False, restore=False): ops.reset_default_graph() graph = ops.get_default_graph() with session.Session( config=_get_config(layout_optimizer), graph=graph) as sess: batch = 2 height = 6 width = 7 input_channels = 3 shape = [batch, height, width, input_channels] image = array_ops.placeholder(dtype='float32', shape=shape) conv1 = conv_layers.conv2d(image, 32, [3, 3]) conv2 = conv_layers.conv2d(conv1, 32, [3, 3]) optimizer = gradient_descent.GradientDescentOptimizer(0.01) loss = math_ops.reduce_mean(conv2) train_op = optimizer.minimize(loss) saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2) if restore: saver.restore(sess, checkpoint_path) else: sess.run(variables.global_variables_initializer()) np.random.seed(0) for _ in range(2): image_val = np.random.rand(*shape).astype(np.float32) sess.run([loss, train_op], feed_dict={image: image_val}) if restore: all_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) all_vars_values = [var.eval(session=sess) for var in all_vars] return all_vars_values else: saver.save(sess, checkpoint_path) def testTwoConvLayers(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) output = _two_layer_model(x) with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Relu_1-0-0', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testSplitWithNonConstAxis(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) dim = array_ops.placeholder(dtype='int32') split = array_ops.split(conv, 2, axis=dim) output = math_ops.reduce_sum(split[0]) with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={dim: 3}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3}) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-split-0-0', nodes) self.assertIn('LayoutOptimizerDimMapNHWCToNCHW_split_0', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testSplitVWithNonConstAxis(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) dim = array_ops.placeholder(dtype='int32') sizes = constant_op.constant([50, 10, 4], shape=[3]) split = gen_array_ops._split_v( value=conv, size_splits=sizes, axis=dim, num_split=3) output = math_ops.reduce_sum(split[0]) with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={dim: 3}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3}) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-SplitV-0-0', nodes) self.assertIn('LayoutOptimizerDimMapNHWCToNCHW_SplitV_2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testPadWithConstPaddings(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]] paddings = constant_op.constant( paddings_val, dtype='int32', name='PaddingsConst') pad = array_ops.pad(conv, paddings) output = array_ops.identity(pad) with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Pad-0-0', nodes) self.assertIn('LayoutOptimizer-Pad-PaddingsConst', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testConcatWithControlDependency(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) axis = constant_op.constant(3) var = variables.Variable(3) assign = state_ops.assign(var, 6) with ops.control_dependencies([assign]): concat = array_ops.concat([conv, conv], axis) output = array_ops.identity(concat) with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-concat-0-0', nodes) self.assertIn('LayoutOptimizer-concat-Const_2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testFill(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = array_ops.placeholder(dtype='float32') conv = _two_layer_model(x) shape = array_ops.shape(conv) scalar = array_ops.constant(5.7) fill = array_ops.fill(shape, scalar) output = array_ops.identity(fill) x_val = [3.4] * 784 with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={x: x_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ x: x_val }) nodes = [] num_transposes = 0 num_vec_permute = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 if node.name.startswith('LayoutOptimizerVecPermute'): num_vec_permute += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) # Two vector permute nodes were initially added in the Expand phase of # LayoutOptimizer; they cancelled out each other in the Collapse phase. expected_vec_permute = 0 self.assertEqual(expected_vec_permute, num_vec_permute) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Fill-0-0', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testReverseWithConstDims(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) dims = constant_op.constant([3, 1], name='DimsConst') reverse = array_ops.reverse(conv, dims) output = array_ops.identity(reverse) with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-ReverseV2-0-0', nodes) self.assertIn('LayoutOptimizer-ReverseV2-DimsConst', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testReverseWithNonConstDims(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) dims = array_ops.placeholder(dtype='int32') reverse = array_ops.reverse(conv, dims) output = array_ops.identity(reverse) dims_val = [2, 3] with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={dims: dims_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ dims: dims_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-ReverseV2-0-0', nodes) self.assertIn('LayoutOptimizerDimMapNHWCToNCHW_ReverseV2_1', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testTernaryOp(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) add = math_ops.add(conv, conv) mean = math_ops.reduce_mean(conv) condition = math_ops.less(conv, mean) select = gen_math_ops._select(condition, conv, add) output = array_ops.identity(select) with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 3 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Select-0-0', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testPadWithNonConstPaddings(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) paddings = array_ops.placeholder(dtype='int32') pad = array_ops.pad(conv, paddings) output = array_ops.identity(pad) paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]] with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={paddings: paddings_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ paddings: paddings_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Pad-0-0', nodes) self.assertIn('LayoutOptimizerVecPermuteNHWCToNCHW_Pad_1', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testMaxPoolV2(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) ksize = constant_op.constant([1, 2, 3, 1], shape=[4]) strides = array_ops.placeholder(dtype='int32', shape=[4]) max_pool = gen_nn_ops._max_pool_v2(conv, ksize, strides, 'VALID') output = array_ops.identity(max_pool) strides_val = [1, 3, 2, 1] with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={strides: strides_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ strides: strides_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-MaxPoolV2-0-0', nodes) self.assertIn('LayoutOptimizerVecPermuteNHWCToNCHW_MaxPoolV2_2', nodes) self.assertIn('LayoutOptimizer-MaxPoolV2-Const_2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testMaxPoolGradV2(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) ksize = constant_op.constant([1, 2, 3, 1], shape=[4]) strides = array_ops.placeholder(dtype='int32', shape=[4]) max_pool_grad = gen_nn_ops.max_pool_grad_v2(conv, conv, conv, ksize, strides, 'VALID') output = array_ops.identity(max_pool_grad) strides_val = [1, 3, 2, 1] with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={strides: strides_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ strides: strides_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-MaxPoolGradV2-0-0', nodes) self.assertIn('LayoutOptimizerVecPermuteNHWCToNCHW_MaxPoolGradV2_4', nodes) self.assertIn('LayoutOptimizer-MaxPoolGradV2-Const_2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testSliceWithNonConstAxis(self): if test.is_gpu_available(cuda_only=True): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) conv = _two_layer_model(x) size = array_ops.placeholder(dtype='int32') s = array_ops.slice(conv, [0, 0, 0, 0], size) output = array_ops.identity(s) size_val = [1, 2, 3, 4] with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={size: size_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ size: size_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Slice-0-0', nodes) self.assertIn('LayoutOptimizerVecPermuteNHWCToNCHW_Slice_2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testShapeN(self): if test.is_gpu_available(cuda_only=True): x = array_ops.placeholder(dtype='float32') conv = _two_layer_model(x) shapen = array_ops.shape_n([conv, conv]) output = math_ops.add(shapen[0], shapen[1]) x_val = [1.7] * 784 with session.Session() as sess: output_val_ref = sess.run(output, feed_dict={x: x_val}) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run( output, run_metadata=metadata, feed_dict={ x: x_val }) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 1 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-Conv2D-0', nodes) self.assertIn('LayoutOptimizerVecPermuteNCHWToNHWC-ShapeN-0-0', nodes) self.assertAllEqual(output_val_ref, output_val) def testLoop(self): if test.is_gpu_available(cuda_only=True): output = _loop() with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) # Four transposes were initially added in the Expand phase of # LayoutOptimizer; two of them are cancelled out in the Collapse phase. expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-map/while/Conv2D-0', nodes) self.assertIn( 'LayoutOptimizerTransposeNCHWToNHWC-map/while/MaxPool_1-0-2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testLoopWithBranch(self): if test.is_gpu_available(cuda_only=True): output = _loop_with_branch() with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-map/while/Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-map/while/Add-0-2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testLoopWithVecAnd4D(self): if test.is_gpu_available(cuda_only=True): output = _loop_with_vec_and_4d() with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-map/while/Conv2D-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-map/while/Add-0-2', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testBinaryOpSecondPort(self): if test.is_gpu_available(cuda_only=True): output = _model_with_second_port() with session.Session() as sess: output_val_ref = sess.run(output) with session.Session(config=_get_config()) as sess: metadata = config_pb2.RunMetadata() output_val = sess.run(output, run_metadata=metadata) nodes = [] num_transposes = 0 for node in metadata.cost_graph.node: if node.name.startswith('LayoutOptimizerTranspose'): num_transposes += 1 nodes.append(node.name) expected_num_transposes = 2 self.assertEqual(expected_num_transposes, num_transposes) self.assertIn('LayoutOptimizerTransposeNHWCToNCHW-FusedBatchNorm-0', nodes) self.assertIn('LayoutOptimizerTransposeNCHWToNHWC-Add-0-0', nodes) self.assertAllClose(output_val_ref, output_val, atol=1e-3) def testGradient(self): meta_graph = _simple_metagraph() rewrite_options = rewriter_config_pb2.RewriterConfig( layout_optimizer=rewriter_config_pb2.RewriterConfig.ON) optimized_graph = tf_optimizer.OptimizeGraph( rewrite_options, meta_graph, cluster=_get_cluster()) found = 0 for node in optimized_graph.node: if node.op in ['Conv2D', 'Conv2DBackpropFilter', 'Conv2DBackpropInput']: found += 1 self.assertEqual(node.attr['data_format'].s, b'NCHW') self.assertEqual(found, 5) def testDepthwise(self): meta_graph = _simple_metagraph(depthwise=True) rewrite_options = rewriter_config_pb2.RewriterConfig( layout_optimizer=rewriter_config_pb2.RewriterConfig.ON) optimized_graph = tf_optimizer.OptimizeGraph( rewrite_options, meta_graph, cluster=_get_cluster()) found = 0 for node in optimized_graph.node: if node.op in [ 'DepthwiseConv2dNative', 'DepthwiseConv2dNativeBackpropFilter', 'DepthwiseConv2dNativeBackpropInput' ]: found += 1 self.assertEqual(node.attr['data_format'].s, b'NCHW') self.assertEqual(found, 6) def testCheckpointCompatibility(self): if not test.is_gpu_available(cuda_only=True): self.skipTest('GPU required') checkpoint_path = self.get_temp_dir() self._train(checkpoint_path) vars_expected = self._train(checkpoint_path, restore=True) vars_layout_optimized = self._train( checkpoint_path, restore=True, layout_optimizer=True) for var_expected, var_layout_optimized in zip(vars_expected, vars_layout_optimized): self.assertAllClose(var_expected, var_layout_optimized, atol=1e-6) if __name__ == '__main__': test.main()
{ "task_name": "lcc" }
Passage 1: Ian Barry (director) Ian Barry is an Australian director of film and TV. Passage 2: Lucciola (1917 film) Lucciola is a 1917 Italian film directed by Augusto Genina. Passage 3: S. N. Mathur S.N. Mathur was the Director of the Indian Intelligence Bureau between September 1975 and February 1980. He was also the Director General of Police in Punjab. Passage 4: Brian Kennedy (gallery director) Brian Patrick Kennedy( born 5 November 1961) is an Irish- born art museum director who has worked in Ireland and Australia, and now lives and works in the United States. He is currently the director of the Peabody Essex Museum. He was the director of the Toledo Museum of Art in Ohio from 2010 to 2019. He was the director of the Hood Museum of Art from 2005 to 2010, and the National Gallery of Australia( Canberra) from 1997- 2004. Passage 5: Peter Levin Peter Levin is an American director of film, television and theatre. Passage 6: Michael Govan Michael Govan( born 1963) is the director of the Los Angeles County Museum of Art since 2006. Prior to this, Govan worked as the director of the Dia Art Foundation in New York City. Passage 7: Augusto Genina Augusto Genina (28 January 1892 – 18 September 1957) was an Italian film pioneer. He was a movie producer and director. Born in Rome, Genina was a drama critic and wrote comedies for the "Il Mondo" Magazine, under advise of Aldo de Benedetti switches to movies for the "Film d'Arte Italiana", that produces his first film "La moglie di sua eccellenza". In 1929 Genina moved to France to direct Louise Brooks in sonorized film "Miss Europe". He studied sound techniques and worked in France and Germany in same but alternate languages film versions which were filmed simultaneously, before his return to Italy. He won Venice Film Festival Mussolini's cup for Best Italian Film twice, in 1936 by "Lo squadrone bianco" and in 1940 by "The Siege of the Alcazar", both Fascist propaganda films. In 1953, he filmed "Three Forbidden Stories", another version of the real accident depicted by Giuseppe De Santis one year before in "Rome 11 o'clockRoma ore 11"). Passage 8: Jesse E. Hobson Jesse Edward Hobson( May 2, 1911 – November 5, 1970) was the director of SRI International from 1947 to 1955. Prior to SRI, he was the director of the Armour Research Foundation. Passage 9: Dana Blankstein Dana Blankstein- Cohen( born March 3, 1981) is the director of the Israeli Academy of Film and Television. She is a film director, and an Israeli culture entrepreneur. Passage 10: Olav Aaraas Olav Aaraas( born 10 July 1950) is a Norwegian historian and museum director. He was born in Fredrikstad. From 1982 to 1993 he was the director of Sogn Folk Museum, from 1993 to 2010 he was the director of Maihaugen and from 2001 he has been the director of the Norwegian Museum of Cultural History. In 2010 he was decorated with the Royal Norwegian Order of St. Olav. Question: Where was the place of death of the director of film Lucciola (1917 Film)? Answer: Rome
{ "task_name": "2WikiMultihopQA" }
Passage 1: Richard Rodgers Richard Charles Rodgers (June 28, 1902 – December 30, 1979) was an American composer, known largely for his work in musical theater. With 43 Broadway musicals and over 900 songs to his credit, Rodgers was one of the most significant American composers of the 20th century, and his compositions had a significant impact on popular music. He is best known for his songwriting partnerships with the lyricists Lorenz Hart, with whom he wrote several musicals throughout the 1920s and 1930s, including "Pal JoeyA Connecticut YankeeOn Your Toes" and "Babes in Arms," and Oscar Hammerstein II, with whom he wrote musicals through the 1940s and 1950s such as "Oklahoma!CarouselSouth PacificThe King and I", and "The Sound of Music". His collaborations with Hammerstein, in particular, are celebrated for bringing the Broadway musical to a new maturity by telling stories that were focused around characters and drama rather than the light-hearted entertainment that the genre was known for beforehand. Rodgers was the first person to win what are considered the top American entertainment awards in television, recording, movies and Broadway – an Emmy, a Grammy, an Oscar, and a Tony Award — now known collectively as an EGOT. In addition, he was awarded a Pulitzer Prize, making him one of only two people to receive all five awards (Marvin Hamlisch is the other). Passage 2: My Love for You " My Love for You" is a song recorded by American R&B singer Sevyn Streeter from her debut studio album," Girl Disrupted"( 2017). The song was released as the first single on September 16, 2016 through Atlantic Records. The song samples" Saving All My Love for You" by Whitney Houston. Passage 3: Alexander Courage Alexander Mair" Sandy" Courage Jr.( December 10, 1919 May 15, 2008) was an American orchestrator, arranger, and composer of music, primarily for television and film. He is best known as the composer of the theme music for the original" Star Trek" series. Passage 4: My Love My Love may refer to: Passage 5: Walter Robinson (composer) Walter Robinson is an African American composer of the late 20th century. He is most notable for his 1977 song" Harriet Tubman", which has been recorded by folk musicians such as Holly Near, John McCutcheon, and others. He is also the composer of several operas. Passage 6: To Keep My Love Alive "To Keep My Love Alive" is a 1943 popular song composed by Richard Rodgers, with lyrics by Lorenz Hart for the 1943 revival of the 1927 musical "A Connecticut Yankee," where it was introduced by Vivienne Segal. It was written especially for Segal. (R&H Theatricals background) It was the last song that Hart wrote before his death from pneumonia. The song outlines the many ways the singer "bumped off" her fifteen husbands in order to avoid being unfaithful to any of them. Some of her methods are arsenic poisoning, stabbing and appendectomy. Passage 7: Ljubavi (Željko Joksimović song) " Ljubavi"( in; English translation:" My love") is the first single from the fifth studio album by Serbian singer- songwriter and music producer Željko Joksimović with the same name. The composer of the song is Željko Joksimović by himself, and the lyrics are written by Momčilo Bajagić- Bajaga. From its release, the song is well charting in most ex-Yugoslav charts. Passage 8: Jerusalem (Dan Bern song) " Jerusalem" is a song by Dan Bern, appearing on his 1996 album," Dan Bern". At the end of the song the singer reveals that he is the messiah. The song opens and closes with the lyrics When I tell you that I love you do n't test my love/ Accept my love/ Do n't test my love/' Cuz maybe I do n't love you all that much This song has been covered by folk singer- songwriter Ani DiFranco. It has been featured in the weather section of the podcast" Welcome to Night Vale". Passage 9: Mark London Mark London( born 30 January 1940 in Montreal, Quebec Canada) is a Canadian born British soundtrack composer, songwriter and music producer. He is perhaps best known as composer of the song" To Sir, with love". Passage 10: Alonso Mudarra Alonso Mudarra( c. 1510 – April 1, 1580) was a Spanish composer of the Renaissance, and also played the vihuela, a guitar- shaped string instrument. He was an innovative composer of instrumental music as well as songs, and was the composer of the earliest surviving music for the guitar. Question: Which country the composer of song To Keep My Love Alive is from? Answer: American
{ "task_name": "2WikiMultihopQA" }
Passage 1: Kaakha Kaakha Kaakha Kaakha (English: "To Protect" ) is a 2003 Tamil-language action drama film written and directed by Gautham Menon. Starring Suriya, Jyothika and Jeevan, the film featured music composed by Harris Jayaraj and cinematography by R. D. Rajasekhar. The film released to highly positive reviews in August 2003 and went on to become the first biggest blockbuster in Suriya's career, and was considered a comeback film for producer Kalaipuli S. Thanu. Owing to the success, the film has been remade in several languages. Passage 2: Mark Strange Mark William Strange (born 8 October 1973) is an English actor, film producer and martial arts action performer. Strange has worked on a number of feature films including "The Medallion" and "The Twins Effect" along with Jackie Chan and "Batman Begins" to name but a few. He has also produced and co-produced feature films, including "Displaced", "Underground", and "Bodyguard: A New Beginning" released in the US by Lionsgate. Passage 3: Thennavan Thennavan is a 2003 Indian Tamil action film written and directed by newcomer M. Nandakumaran and produced by Vijayakanth, who played the title role Thennavan IAS, in-charge as the Chief Election Commissioner and fight against corrupted politicians.The musical score by Yuvan Shankar Raja.The film released on 15 August 2003, coinciding with India's Independence Day. It was later dubbed in Telegu as "Election Commissioner". Passage 4: Michael Misick Michael Eugene Misick ( ; born 2 February 1966) is the former chief minister of the Turks and Caicos Islands from 15 August 2003 to 9 August 2006 and was the first Premier of the Turks and Caicos Islands from 9 August 2006 to 23 March 2009. Misick is a member of the liberal Progressive National Party (PNP), and became chief minister when his party, after eight years as the opposition party, gained two parliamentary seats in by-elections. In addition to being premier, he was also the minister for Civil Aviation, Commerce and Development, Planning, District Administration, Broadcasting Commission, Tourist Board, Turks and Caicos Investment Agency, and Tourism. Several other members of Misick's family have been politicians in the Turks and Caicos Islands, and important leaders in the PNP. Washington Misick, his brother, is a former Chief Minister and currently Minister of Finance, following elections in November 2012, in which the PNP returned to power. Passage 5: Raghu Romeo Raghu Romeo is a 2003 Bollywood film directed by Rajat Kapoor, starring Vijay Raaz, Sadiya Siddiqui, Maria Goretti, Manu Rishi and Saurabh Shukla. The film released on 15 August 2003 to critical acclaim but was a big commercial failure. Set in modern-day Mumbai, the film focuses on the life of a waiter working in a dance bar. The film won the National Film Award for Best Feature Film in Hindi. Passage 6: Italian nationality law Italian nationality law is the law of Italy governing the acquisition, transmission and loss of Italian citizenship. Like many continental European countries it is largely based on "jus sanguinis". It also incorporates many elements that are seen as favourable to the Italian diaspora. The Italian Parliament's 1992 update of Italian nationality law is Law no. 91, and came into force on 15 August 1992. Presidential decrees and ministerial directives, including several issued by the Ministry of the Interior, instruct the civil service how to apply Italy's citizenship-related laws. Passage 7: The Medallion The Medallion () is a 2003 American-Hong Kong action-comedy film co-written and directed by Hong Kong filmmaker Gordon Chan, and starring Jackie Chan, Lee Evans, Claire Forlani and Julian Sands. It was much less successful than Chan's other American movies such as the "Rush Hour" film series, "Shanghai Noon" and its sequel, "Shanghai Knights". The film was theatrically released on 15 August 2003 in Hong Kong and 22 August 2003 in the United States by TriStar Pictures. Passage 8: Tito Junco (Cuban actor) Tito Junco (4 January 1944 – 15 August 2003) was a Cuban film actor. He appeared in 19 films and television shows between 1975 and 2003. In 1981 he won the award for Best Actor at the 12th Moscow International Film Festival for his role in "Guardafronteras". Passage 9: Aadanthe Ado Type Aadanthe Ado Type is a 2003 Indian Telugu romance film directed by E V V Satyanarayana with Sivaji, Aryan Rajesh and Anita Hassanandani in lead roles. It is a remake of the 2002 Tamil film "Mounam Pesiyadhe" written and directed by Ameer Sultan, with Aryan Ramesh, Anita, Shivaji, Sindhu and Bhoomika replacing Surya, Trisha Krishnan, Nandha, Maha and Laila, respectively, who originally played the roles. The film released on 30 August 2003. There is also a dubbed Telugu version of "Mounam Pesiyadhe", titled as "Kanchu", which released in 2006. Passage 10: Mazen Dana Mazen Dana (Arabic: مازن دعنا‎ ‎ , 1962—17 August 2003) was a Palestinian journalist who worked as a Reuters cameraman. He spent a decade covering the Israeli-Palestinian conflict in Hebron in the West Bank, for which he was awarded the 2001 International Press Freedom Award of the Committee to Protect Journalists. He was shot and killed by US soldiers in Baghdad, Iraq on 17 August 2003. Question: This film released on 15 August 2003 was worked on by an actor and film producer of what nationality? Answer: English
{ "task_name": "hotpotqa" }
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Bot.Connector { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; /// <summary> /// Attachments operations. /// </summary> public partial class Attachments : IServiceOperations<ConnectorClient>, IAttachments { /// <summary> /// Initializes a new instance of the Attachments class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Attachments(ConnectorClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ConnectorClient /// </summary> public ConnectorClient Client { get; private set; } /// <summary> /// GetAttachmentInfo /// </summary> /// Get AttachmentInfo structure describing the attachment views /// <param name='attachmentId'> /// attachment id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<object>> GetAttachmentInfoWithHttpMessagesAsync(string attachmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("attachmentId", attachmentId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetAttachmentInfo", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/attachments/{attachmentId}").ToString(); _url = _url.Replace("{attachmentId}", Uri.EscapeDataString(attachmentId)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationResponse<object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<AttachmentInfo>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 400) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 401) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 403) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 404) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 500) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 503) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GetAttachment /// </summary> /// Get the named view as binary content /// <param name='attachmentId'> /// attachment id /// </param> /// <param name='viewId'> /// View id from attachmentInfo /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<object>> GetAttachmentWithHttpMessagesAsync(string attachmentId, string viewId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } if (viewId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "viewId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("attachmentId", attachmentId); tracingParameters.Add("viewId", viewId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetAttachment", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/attachments/{attachmentId}/views/{viewId}").ToString(); _url = _url.Replace("{attachmentId}", Uri.EscapeDataString(attachmentId)); _url = _url.Replace("{viewId}", Uri.EscapeDataString(viewId)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 301 && (int)_statusCode != 302 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationResponse<object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 400) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 401) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 403) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 404) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 500) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } // Deserialize Response if ((int)_statusCode == 503) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
{ "task_name": "lcc" }
<html> <head><title>Friday the 13th Part VIII: Jason Takes Manhattan Script at IMSDb.</title> <meta name="description" content="Friday the 13th Part VIII: Jason Takes Manhattan script at the Internet Movie Script Database."> <meta name="keywords" content="Friday the 13th Part VIII: Jason Takes Manhattan script, Friday the 13th Part VIII: Jason Takes Manhattan movie script, Friday the 13th Part VIII: Jason Takes Manhattan film script"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="HandheldFriendly" content="true"> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <meta http-equiv="Content-Language" content="EN"> <meta name=objecttype CONTENT=Document> <meta name=ROBOTS CONTENT="INDEX, FOLLOW"> <meta name=Subject CONTENT="Movie scripts, Film scripts"> <meta name=rating CONTENT=General> <meta name=distribution content=Global> <meta name=revisit-after CONTENT="2 days"> <link href="/style.css" rel="stylesheet" type="text/css"> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-3785444-3']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body topmargin="0" bottommargin="0" id="mainbody"> <table width="99%" border="0" cellspacing="0" cellpadding="0" class="body"> <tr> <td valign="bottom" bgcolor="#FF0000"><a href="https://www.imsdb.com" title="The Internet Movie Script Database"><img src="/images/logo_top.gif" border="0"></a></td> <td bgcolor="#FF0000"> <center> <font color="#FFFFFF"><h1>The Internet Movie Script Database (IMSDb)</h1></font> </center> <tr> <td background="/images/reel.gif" height="13" colspan="2"><a href="https://www.imsdb.com" title="The Internet Movie Script Database"><img src="/images/logo_middle.gif" border="0"></a></td> <tr> <td width="170" valign="top" class="smalltxt"> <a href="https://www.imsdb.com" title="The Internet Movie Script Database"><img src="/images/logo_bottom.gif" width="170" border="0"></a> <br> <center><span class="smalltxt">The web's largest <br>movie script resource!</span></center> </td> <td> <script type="text/javascript"><!-- e9 = new Object(); e9.size = "728x90"; //--></script> <script type="text/javascript" src="//tags.expo9.exponential.com/tags/IMSDb/ROS/tags.js"></script> </td> </tr> </table> <br> <table width="99%" border="0" cellspacing="0" cellpadding="0" class="body"> <tr> <td width="180" valign="top"> <table class=body border=0 cellspacing=0 cellpadding=2 width="100%"> <tr> <td colspan="2" class=heading>Search IMSDb<tr> <form method="post" action="/search.php"> <td width="180"> <div align="center"> <input type="text" name="search_query" maxlength="255" size="15"> <input type="submit" value="Go!" name="submit"> </div></td> </form> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td colspan=9 class=heading>Alphabetical <tr align="center"> <td><a href="/alphabetical/0">#</a> <td><a href="/alphabetical/A">A</a> <td><a href="/alphabetical/B">B</a> <td><a href="/alphabetical/C">C</a> <td><a href="/alphabetical/D">D</a> <td><a href="/alphabetical/E">E</a> <td><a href="/alphabetical/F">F</a> <td><a href="/alphabetical/G">G</a> <td><a href="/alphabetical/H">H</a><tr align="center"> <td><a href="/alphabetical/I">I</a> <td><a href="/alphabetical/J">J</a> <td><a href="/alphabetical/K">K</a> <td><a href="/alphabetical/L">L</a> <td><a href="/alphabetical/M">M</a> <td><a href="/alphabetical/N">N</a> <td><a href="/alphabetical/O">O</a> <td><a href="/alphabetical/P">P</a> <td><a href="/alphabetical/Q">Q</a><tr align="center"> <td><a href="/alphabetical/R">R</a> <td><a href="/alphabetical/S">S</a> <td><a href="/alphabetical/T">T</a> <td><a href="/alphabetical/U">U</a> <td><a href="/alphabetical/V">V</a> <td><a href="/alphabetical/W">W</a> <td><a href="/alphabetical/X">X</a> <td><a href="/alphabetical/Y">Y</a> <td><a href="/alphabetical/Z">Z</a> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td colspan=3 class=heading>Genre <tr> <td><a href="/genre/Action">Action</a> <td><a href="/genre/Adventure">Adventure</a> <td><a href="/genre/Animation">Animation</a><tr> <td><a href="/genre/Comedy">Comedy</a> <td><a href="/genre/Crime">Crime</a> <td><a href="/genre/Drama">Drama</a><tr> <td><a href="/genre/Family">Family</a> <td><a href="/genre/Fantasy">Fantasy</a> <td><a href="/genre/Film-Noir">Film-Noir</a><tr> <td><a href="/genre/Horror">Horror</a> <td><a href="/genre/Musical">Musical</a> <td><a href="/genre/Mystery">Mystery</a><tr> <td><a href="/genre/Romance">Romance</a> <td><a href="/genre/Sci-Fi">Sci-Fi</a> <td><a href="/genre/Short">Short</a><tr> <td><a href="/genre/Thriller">Thriller</a> <td><a href="/genre/War">War</a> <td><a href="/genre/Western">Western</a> </table> <br> <table class=body border=0 cellspacing=0 cellpadding=2 width="100%"> <tr> <td colspan="2" class=heading>Sponsor<tr> <td width="300" bgcolor="#FFFFFF"> <script type="text/javascript"><!-- e9 = new Object(); e9.size = "300x250"; //--></script> <script type="text/javascript" src="//tags.expo9.exponential.com/tags/IMSDb/ROS/tags.js"></script> </td> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td class=heading>TV Transcripts <tr> <td><a href="/TV/Futurama.html">Futurama</a><tr> <td><a href="/TV/Seinfeld.html">Seinfeld</a><tr> <td><a href="/TV/South Park.html">South Park</a><tr> <td><a href="/TV/Stargate SG1.html">Stargate SG-1</a><tr> <td><a href="/TV/Lost.html">Lost</a><tr> <td><a href="/TV/The 4400.html">The 4400</a> </table> <br> <table width="100%" class="body"> <tr> <td colspan=3 class=heading>International <tr> <td><a href="/language/French">French scripts</a> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td class=heading>Movie Software <tr> <td><a href="/out/dvd-ripper"><img src="/images/a/dvd-ripper.jpg" alt="DVD ripper software offer"></a> <tr> <td><a href="/software/rip-from-dvd">Rip from DVD</a> <tr> <td><a href="/software/rip-blu-ray">Rip Blu-Ray</a> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td colspan=3 class=heading>Latest Comments <tr> <td><a href="/Movie Scripts/Star Wars: Revenge of the Sith Script.html">Star Wars: Revenge of the Sith<td>10/10<tr> <td><a href="/Movie Scripts/Star Wars: The Force Awakens Script.html">Star Wars: The Force Awakens<td>10/10<tr> <td><a href="/Movie Scripts/Batman Begins Script.html">Batman Begins<td>9/10<tr> <td><a href="/Movie Scripts/Collateral Script.html">Collateral<td>10/10<tr> <td><a href="/Movie Scripts/Jackie Brown Script.html">Jackie Brown<td>8/10<tr> </table> <br> <table width="100%" border=0 cellpadding=2 cellspacing=0 class=body> <tr> <td class=heading>Movie Chat <tr> <td align="center"> <SCRIPT LANGUAGE="Javascript" TYPE="text/javascript" SRC="https://www.yellbox.com/ybscript_enhanced.js"></SCRIPT> <iframe class="yellbox" frameborder=0 name="ybframe" height=170 marginwidth=0 marginheight=0 src="https://www.yellbox.com/yellbox.php?name=imsdb"> </iframe> <form class="yellbox" action="https://www.yellbox.com/addmessage.php" method="post" target="ybframe" name="yellform"> <input type="hidden" name="sub_username" value="imsdb"> <input class="yellbox" name="sub_name" value="Name" size=21 maxlength=10 onFocus="if(this.value == 'Name')this.value = ''; return;"><br> <textarea class="yellbox" cols=15 rows=4 name="sub_message" wrap onFocus="if(this.value == 'Message')this.value = ''; return;">Message</textarea> <table><tr><td> <button onClick="javascript:makeNewWindow(); return false;"><img src="https://www.yellbox.com/images/smiley.gif" width=16 height=16></button> <td><button type="submit" value="Post" onClick="return clearMessageBox();">Yell !</button></table> </form> </table> <div align="center"><br><br> <a href="https://www.imsdb.com/all%20scripts">ALL SCRIPTS</a><br><br> </div> <td width="10"></td> <td valign="top"> <br> <table width="100%"><tr><td class="scrtext"> <pre><html> <head> <script> <b><!-- </b>if (window!= top) top.location.href=location.href <b>// --> </b></script> <title>FRIDAY THE 13TH PART VIII: JASON TAKES MANHATTAN </title> </head> <pre> <b> FRIDAY THE 13TH PART VIII: JASON TAKES MANHATTAN </b> Written by Rob Hedden <b> FADE IN: </b> <b> EXT. CRYSTAL LAKE - NIGHT </b> A dark, rumbling sky. Haze clings to the lake as we float across it, clearing to bring the opposite shoreline into view. A few scattered streetlights. Dilapidated cabins. An abandoned campsite. CAMP CRYSTAL LAKE. We continue to drift towards it, hearing the faint sound of seductive music and an occasional giggle. A small HOUSEBOAT floats into our foreground, its interior light flickering as TWO BODIES move around inside. <b> INT. HOUSEBOAT - NIGHT </b> A teenage boy and girl, JIM and SUZY, are slow-dancing. Jim's lips softly touch her lissome shoulders. <b> JIM </b> Well...how do you feel? <b> SUZY </b> Ask me in about five minutes. She bites his ear, giggles, then kisses him fully.. <b> JIM </b> I'm talking about graduation. Being totally free to do whatever we want now. Her hands slip inside his Pendleton shirt. He sighs. <b> SUZY </b> It feels excellent. Her mouth finds his again. After a long kiss, he gently pulls away from her with a teasing smile. <b> JIM </b> Gotta throw the anchor over. He leaves the cabin. She slips under the bed sheets. <b> EXT. HOUSEBOAT DECK - NIGHT </b> as Jim tosses a small anchor overboard. <b> TIGHT ON WATER SURFACE </b> as the weighty object splashes, sinking into black oblivion, pulling its cable down with it. <b> JIM </b> glances at the lake, at their eerie surroundings. He feels a chill, heading back inside. <b> EXT. UNDERWATER - NIGHT (TANK) </b> as the anchor drifts to the lake bottom, dropping a few feet from a THICK POWER CABLE which rests in the lake silt. <b> INT. HOUSEBOAT - NIGHT </b> as Jim returns with an uneasy expression. He crawls on top of the bed, kissing her again, but not with the same enthusiasm as before. <b> SUZY </b> What's wrong? <b> JIM </b> Nothing. He starts to pull off his shirt and join her. She senses his anxiety. <b> SUZY </b> C'mon, Jimmy. Something's bothering you. Jim pauses, turning off the mood music. <b> JIM </b> It's just that we're right around that old summer camp where all those murders took place. The boat creaks. She's instantly nervous. <b> SUZY </b> What murders? <b> JIM </b> Never mind, you don't want to know about it. <b> SUZY </b> Tell me. <b> JIM </b> There's nothing to worry about, Suzy. The guy's dead now, somewhere at the bottom of this lake...if you believe the stories. (beat) Let's drop it, okay? He starts to kiss her again. She stops him. <b> SUZY </b> What stories? He doesn't want to go into it but Suzy's face insists. <b> JIM </b> There was this boy named Jason Voorhees who drowned in Crystal Lake... <b> FLASHBACK </b> Eight year old JASON is desperately trying to tread water, flailing his arms like a marionette to get attention as he gulps down gallons of mossy lake water. <b> YOUNG JASON </b> Hhhhelp....me....I'm drowning... <b> JIM (V.O.) </b> None of the counselors heard him. <b> YOUNG JASON </b> Mmmmmmommy.... ...And Jason finally slips under the surface for good. <b> INT. HOUSEBOAT - CONTINUOUS </b> <b> JIM </b> A bunch of years went by and everybody forgot about it. (beat) That's when the murders started. <b> FLASHBACK MONTAGE (STOCK) </b> as our senses are bombarded with QUICK CUTS of assorted teenagers just about to die, their screams echoing over each other. We do not see the attacker. As the cacophony reaches a screeching crescendo, CUT BACK TO: <b> INT. HOUSEBOAT - NIGHT </b> as the silence hits us hard again. <b> SUZY </b> Jason did it...? <b> JIM' </b> That's what some people thought. But they were wrong. <b> FLASHBACK (STOCK) </b> as MRS. VOORHEES comes directly at camera wielding a huge knife and a primal scream. <b> INT. HOUSEBOAT - NIGHT </b> <b> JIM </b> His mother blamed the counselors for his death and tried to kill them all. (dramatic pause) She got her head chopped off by one of them. We don't need to see this clip...Suzy's reaction is quite sufficient. <b> SUZY </b> So the murders stopped? He gives her a long, penetrating look. <b> JIM </b> No. <b> FLASHBACK MONTAGE (STOCK) </b> We're bombarded with QUICK FLASHES of a hockey masked JASON wreaking havoc on assorted teenagers...brandishing everything from hatchets to knives to chainsaws. Just as Jason is about to stab us, CUT BACK TO: <b> INT. HOUSEBOAT - NIGHT </b> Suzy flinches as if she were getting the knife. <b> </b> <b> JIM </b> Legend has it that Jason came back to avenge his mother's death, vowing to kill every teenager from the area. (beat) And every now and then, the murders start up again. The boat lurches slightly, tugging at the anchor cable. She's scared: he's frightened himself a little, too. <b> JIM </b> Forget about it, Suzy. They're just stories. He brushes her hair back, kissing her cheek gently, finding the nape of her neck again. She closes her eyes, trying to dismiss what he's dredged up. But she can't. Suzy begins to rationalize. <b> SUZY </b> We're the last graduating class, right? Jim's kissing her body, putting Jason behind him. <b> JIM </b> Right. <b> SUZY </b> I mean, Lakeview High just closed its doors for good, right? <b> JIM </b> Right. <b> SUZY </b> So there's no reason for him to come back because there won't be any of us around...right? Jim stops, looking her squarely in the eyes. <b> JIM </b> Right. Except that Jason isn't real so none of it matters anyway. She starts to relax, returning his kisses. <b> EXT. UNDERWATER - NIGHT (TANK) </b> as the anchor drifts along the lake floor, tugging hard on the power cable. Camera TRACKS along the cable, coming to a RUSTY SET OF CHAINS TANGLED AROUND IT. <b> INT. HOUSEBOAT - CONTINUOUS </b> as Jim slides on top of Suzy. Thoughts of Jason are starting to slip away along with their clothes. <b> EXT. UNDERWATER - NIGHT (TANK) </b> as the chains emit a dull tinkle due to movement from the tugging anchor. Camera continues to TRACK again...and we find to our horror that the waterlogged, fish-eaten body of JASON IS SECURED BY THESE SAME CHAINS. (NOTE: Jason's face is obscured.) <b> INT. HOUSEBOAT - CONTINUOUS </b> Teenagers in love, lost in not-so-innocent passion. At the same moment: <b> EXT. UNDERWATER - NIGHT (TANK) </b> The anchor tugs one last time and RIPS THROUGH THE CABLE. SPARKS INSTANTLY FLY, chasing along the cable, finding the chain which secures Jason and ENGULFING HIM IN <b> ELECTRICITY. </b> <b> EXT. HOUSEBOAT - ON LAKE SURFACE (EFX) </b> as BRIGHT FLASHES OF BLUE LIGHT strobe-under the surface. ARCING CURRENT chases up the anchor cable, sparking across the hoist. <b> EXT. CAMP CRYSTAL LAKE - WIDE SHOT FROM WATER </b> as the electricity feeding the streetlights is abruptly extinguished, plunging the campsite into darkness. <b> INT. HOUSEBOAT - CONTINUOUS </b> as Suzy's eyes flash open. <b> SUZY </b> Did you hear that? <b> JIM </b> Hear what? He pulls her back down. <b> SUZY </b> C'mon, I'm serious. He knows the mood is broken. <b> JIM </b> All right, I'll check it out. He slips on his jeans, exiting the cabin. She pulls the sheet up around her fearfully. <b> EXT. UNDERWATER - NIGHT (TANK) </b> as the cable smolders, void of electricity now. TRACK to find the chains again...but they're dangling loosely. <b> JASON IS GONE. </b> <b> INT. HOUSEBOAT - CONTINUOUS </b> Suzy is tensely kneeling on the bed now. The black void of night is all she sees out the cabin door, which Jim has left open. An uncomfortable amount of time passes. <b> SUZY </b> Jimmy...? No answer. Her heart starts to pound. <b> SUZY </b> Jim...? Again, nothing. She wraps herself in the sheet, moving towards the open door. The ship creaks again. <b> SUZY'S POINT OF VIEW </b> as she grows closer to the doorway, nothing but pitch- black beyond it. <b> SUZY </b> Stop screwing around, Jim. I mean it... ...And just as she reaches the door: <b> A HOCKEY MASKED MONSTER </b> leaps out, clutching a HUGE KNIFE. Suzy barely has time to scream before JASON PLUNGES THE KNIFE INTO HER CHEST. <b> SUZY </b> stands there in speechless shock, looking down at her mortal wound. But there's no blood. <b> THE MONSTER </b> pulls the knife back out, pushing the blade in and out with his hand. It's a retractable rubber knife. JIM pulls off the hockey mask with a huge grin, tossing it aside. <b> JIM </b> Gotcha good, baby cakes. She doesn't know whether to hug him with relief or kick him in the balls. He pulls her back onto the bed, laughing. <b> EXT. HOUSEBOAT - CLOSE ON HOCKEY MASK </b> sitting dormant on the deck, where Jim tossed it. A SHADOW FALLS ACROSS IT...followed by a SLIMY, DECOMPOSING HAND. The hand grabs it like it's an old friend, pulling it away. <b> INT. HOUSEBOAT - CONTINUOUS </b> as Jim holds his angry girlfriend down on the bed, trying unsuccessfully to kiss her. <b> JIM </b> All right, all right -- I'm a major ass. <b> SUZY </b> And you'll never do it again. <b> JIM </b> And I'll never do it again. Forgive me? <b> SUZY </b> No. She's resisting only for effect. Her legs curl around him, finally giving in. <b> EXT. HOUSEBOAT - NIGHT </b> A deadly-sharp SPEAR GUN rests in its rack outside the cabin. JASON'S HAND REMOVES IT. <b> INT. HOUSEBOAT - CONTINUOUS </b> The sheets begin to roll like waves as they work each other. Thoughts of Jason are nonexistent now. <b> ANGLE - CABIN DOOR </b> Nothing there for a moment...then a pair of moss-covered <b> BARE FEET SLOSH INTO FRAME. </b> <b> SUZY </b> closes her eyes with pleasure... <b> ANGLE - CABIN DOOR </b> ...and camera RISES from the mossy feet, up the bloodless legs and torso to ultimately reveal the hockey-masked face of our anti-hero: JASON VOORHEES. <b> SUZY </b> lets out a broad smile, her eyelids fluttering. They stay open long enough to regard the visitor in the doorway. She tries to choke out a warning to Jim, who's just collapsed himself. <b> SUZY </b> JJJJJJJJason... He doesn't follow her glance, smiling instead. <b> JIM </b> Uh-huh. You must really think I'm an ass. But she continues to stare in horror as: <b> JASON </b> raises the spear, taking aim. <b> ANGLE - SUZY AND JIM </b> Hs starts to kiss her but she bolts up with a blood- curdling SCREAM. A second later, JASON FIRES THE SPEAR, <b> PIERCING HER NECK, PINNING HER TO THE HEAD BOARD. </b> Jim stares point-blank at his dead girlfriend, not able to assimilate it quickly enough. He spins around to see the monster himself. <b> JIM </b> Ohmygod... Jim springs off the bed, looking around for anything to defend himself with, grabbing the bedside lamp. He SMASHES IT OVER JASON'S HEAD which has little effect. Jim scrambles to get past him, but Jason LIFTS JIM IN THE <b> AIR, SLAMMING HIM DOWN ON ONE OF THE SPIKED BEDPOSTS. </b> <b> EXT. CRYSTAL LAKE - NIGHT </b> as the HOUSEBOAT silently drifts onward. The lone silhouette of Jason emerges from within, taking the helm. He's back. <b> FADE OUT/MAIN CREDITS. </b> <b> FADE IN: </b> <b> EXT. HARBOR - ESTABLISHING - DAY </b> Only the faintest sign of daylight can be seen through a thick blanket of gray fog. In the distance, speckled lights outlining a smaller LUXURY CRUISE SHIP intermittently appear. <b> EXT. DOCKSIDE - DAY </b> Standing at the boarding ramp is CHARLES MCCULLOCH, clipboard in hand. He's just finished checking off a pair of new-agey SENIOR GIRLS. McCulloch is approaching fifty, wearing a tie and unwrinkled clothes, as well as the disposition of a stern puritan. <b> MCCULLOCH </b> Remember girls, the shuffleboard tournament will start at six p.m. sharp. A non-attendance will restrict your time in port, understood? They nod for his benefit, exchanging derogatory whispers as they head up the ramp. Camera ADJUSTS to find a small parking lot adjacent to the docks, where several cars are just now arriving -- parents dropping off their high school seniors, hugging them bon voyage. <b> CLOSER ANGLE PARKING LOT </b> as SEAN ROBERTSON walks toward the ship with pal MILES WOLFE. Sean's a tall, nice looking, somewhat serious guy; Miles is shorter, athletic and more extroverted. <b> MILES </b> You're telling me this boat has a pool with a three meter board? <b> SEAN </b> It's a ship and that's right. Plus a disco, gym, game room and a lot more. <b> MILES </b> I think I'm gonna blow off New York and just stay on this thing. <b> MCCULLOCH </b> You'll do no such thing, Mr. Wolfe... Camera ADJUSTS to reveal McCulloch, holding his list, checking off their names. <b> MCCULLOCH </b> Your itinerary has been carefully planned and make no mistake, it will be executed accordingly. <b> MILES </b> (under his breath) Of course...wouldn't want to risk enjoying this trip. McCulloch gives him a frown. Sean steps up to him tentatively. <b> SEAN </b> Which cabin is Rennie in, Mr. McCulloch? <b> MCCULLOCH </b> Rennie's not coming. He's devastated. <b> SEAN </b> But I thought... <b> MCCULLOCH </b> She changed her mind. (eyeing list) Let's see...Mr. Wolfe is in stateroom one-eleven and you, Mr. Robertson, are in two-twenty-five. A booming VOICE from above interrupts them: <b> ADMIRAL ROBERTSON (O.S.) </b> Sean -- where the hell have you been? We're already into early departure protocol... <b> ANOTHER ANGLE </b> Standing on the upper deck is a no-nonsense, uniformed Navy man, ADMIRAL ROBERTSON. The captain of the ship. And Sean's father. Sean's sadness about Rennie's absence is immediately replaced with anxiety. <b> SEAN </b> Be right up, Dad. He and Miles head up the gangway, both boys giving McCulloch one last glare. <b> INT. '76 BMW 2002 - DAY </b> Behind the wheel is MISS COLLEEN VAN DEUSEN, thirties, attractive, a progressive attitude. RENNIE WICKHAM sits next to her -- she's seventeen, pretty, slightly withdrawn. Rennie's dog TOBY, a border collie, rides in the back seat. <b> MISS VAN DEUSEN </b> I'm glad you decided to come after all. <b> RENNIE </b> Me too. But I'm not sure Uncle Charles will be. <b> MISS VAN DEUSEN </b> You let me worry about him, okay? (pause) Personal experiences are what fuel the minds of great writers, Rennie. You made the right decision. <b> RENNIE </b> What about not-so-great writers? Rennie smiles self-deprecatingly, Miss Van Deusen grinning back. But Rennie's smiles are few and far between, this one disappearing as she glances out the window. <b> RENNIE'S POINT OF VIEW (SECOND UNIT) </b> as the countless gallons of harbor and lake water spread out before her, eery in the bog. A small ROWBOAT grazes across it occupied by two indistinguishable people. <b> RETURN TO SHOT </b> Rennie's eyes show a hidden terror. She quickly turns away, shivering briefly. Miss Van Deusen notices. She turns a corner, heading into the parking lot. <b> MISS VAN DEUSEN </b> Everything okay? <b> RENNIE </b> Just felt a little chill. Rennie rubs her arms, faking coldness. <b> MISS VAN DEUSEN </b> Did you know that I'm giving up teaching? <b> RENNIE </b> Really? <b> MISS VAN DEUSEN </b> Since the school is closing anyway, I'm going to write that novel I've been threatening on everybody. <b> RENNIE </b> That's wonderful, Miss Van Deusen...what's it about? She parks the car, turning off the ignition. <b> MISS VAN DEUSEN </b> A senior class cruise to Manhattan, laced with romance, adventure and murder. (beat) Or a Gothic cook book. I haven't decided which. She's coaxed the smile out of Rennie again. Miss Van Deusen pulls a small wrapped box from her glove compartment, handing it to Rennie, who seems utterly surprised. <b> MISS VAN DEUSEN </b> Go on, open it. Rennie pops off the lid, revealing an antique ink-dip pen. <b> MISS VAN DEUSEN </b> Stephen King supposedly used it when he was in high school. <b> RENNIE </b> I don't know what to say... <b> MISS VAN DEUSEN </b> Rennie, you're the best student I ever had...you have a real gift. If anybody can make use of that pen, it's you. Rennie hugs her teacher. Camera RISES above the car's window, finding a Mercedes 560 SL pulling in a short distance away. <b> CLOSER ANGLE - MERCEDES </b> A sexy, money-dressed blonde is behind the wheel. TAMARA MASON. She climbs from her leather seats as a trio of SENIOR GIRLS walk by, offering enthusiastic hi's and hellos. She's obviously Miss Popular. Tamara crosses to a cute Japanese girl unloading luggage from a beige Honda, <b> EVA WATANABE. </b> <b> . TAMARA </b> Are you ready for drugs, sex and rock 'n roll or what, girl? Eva gives her a warning glance, nodding to her left. Eva's MOTHER appears by the passenger door, forcing a smile at Tamara. <b> MRS. WATANABE </b> Hello, Tamara. <b> TAMARA </b> Hi, Mrs. Watanabe. Just kidding. <b> MRS. WATANABE </b> Yes, I'm sure. Embarrassed, Eva hurries to her Mom, rushing a kiss goodbye. <b> EVA </b> Don't worry about a thing, Mom. I'll have a terrific time and I won't do anything stupid, okay? Before Mrs. Watanabe can squeeze a word in, her daughter is gone. She waves a bittersweet goodbye to her graduate. <b> MRS. WATANABE </b> I love you... <b> TRACKING WITH TAMARA AND EVA </b> Once they're out of Mrs. Watanabe's earshot -- <b> TAMARA </b> I hear the crew members are cute guys in their twenties. <b> EVA </b> Really? <b> TAMARA </b> I'm sure we'll have no problem getting them to party with us...especially with this. Tamara unzips her purse, revealing a baggie filled with fine white powder. Eva looks very nervous. <b> TAMARA </b> It's my graduation gift from Daddy. It cost over a thousand bucks but it's the best. <b> EVA </b> He bought you that? <b> TAMARA </b> More or less. It's part of my college fund. <b> </b> She grins coquettishly, walking on. Camera HOLDS on the calm, foggy harbor...where the faint image of a HOUSEBOAT is aimlessly drifting into port. <b> CLOSER ANGLE - HOUSEBOAT </b> Sure enough, it's the same one we saw JASON on last night...but no one is behind the helm. It seems to be a ghost ship. <b> EXT. DOCKSIDE - DAY </b> as Tamara tries to slip past McCulloch, busy with another pair of seniors. <b> MCCULLOCH </b> You can stop right there, Miss Mason. He motions the others onward. Busted. Tamara instantly hands Eva her drug-filled purse, paralyzing Eva. <b> MCCULL40CH </b> Only graduating seniors are allowed on this cruise. <b> TAMARA </b> What are you talking about? <b> MCCULLOCB </b> You never turned in your final biology project, so I've had your diploma rescinded. <b> TAMARA </b> You can't do that... <b> MCCULLOCH </b> It's already been done. (turning to Eva) Congratulations on the 3.9 average, Miss Watanabe. You're in stateroom two- fifty-five. Eva smiles awkwardly, reaching for her luggage, stalling to see what happens with Tamara. <b> TAMARA </b> Look, Mr. McCulloch, I got in a car accident yesterday and missed our appointment. It's okay, no big deal, just a bruised arm... (squeezes her arm) ...so I brought my project along today. It's in my suitcase. Really. He looks at her suitcase, not buying a word of this. <b> EVA </b> She's telling the truth, Mr. McCulloch. I saw her pack it. He's surprised to hear this...and so is Tamara. <b> MCCULLOCH </b> All right. But if it mysteriously disappears en route, I'll have you sent back home the minute we dock. Understood? <b> TAMARA </b> Perfectly. She grabs her purse back from Eva, quickly moving on before he changes his mind. Their voices become whispers. <b> TAMARA </b> A major prick. <b> EVA </b> What are you going to do? <b> TAMARA </b> Improvise, of course. <b> EXT. DOCK PILINGS - SAME TIME </b> as the HOUSEBOAT haphazardly bumps into barnacle-covered dock pilings, still around fifty yards from the cruise ship. <b> POINT OF VIEW OUT HOUSEBOAT WINDOW </b> The window is splattered with blood, but still clear enough to make out Tamara and Eva walking up the gangway, along with a half dozen other teenagers mingling on board. <b> TIGHT ON HOUSEBOAT'S ANCHOR CABLE </b> --or rather the remnants of it. It's a piece of frayed woven metal charred by extreme electricity, severed just above water level. Suddenly there's blurry movement behind it; camera RACK FOCUSES just in time to catch a glimpse of JASON SLIPPING OFF THE SIDE, FLOATING TOWARDS <b> THE PILINGS. </b> <b> EXT. DOCKSIDE - SAME TIME </b> as McCulloch impatiently checks his watch and list again. Miss Van Deusen walks up to him. <b> MISS VAN DEUSEN </b> Hello, Charles. Has everyone checked in? <b> MCCULLOCH </b> Jim Miller and Suzy Donaldson never showed up. I'm a little concerned. <b> MISS VAN DEUSEN </b> Don't be. They probably decided to explore each other rather than New York. He gives her a disdainful look, starting up the ramp. <b> MCCULLOCH </b> Let's go -- we're running two minutes late. <b> MISS VAN DEUSEN </b> Charles, there's someone else coming along too. He stops, following her glance. His face tightens. <b> ANOTHER ANGLE </b> Rennie is walking toward them with a small suitcase, her dog Toby striding next to her. She walks up to him, starts to say something, then decides against it. Rennie heads up the gangway. HOLD on McCulloch and Miss Van Deusen. He's livid. <b> MCCULLOCH </b> You have no right... <b> MISS VAN DEUSEN </b> And neither do you. It's up to Rennie to decide what she wants to do. <b> MCCULLOCH </b> She doesn't know what she wants. She's never had a stable life. <b> MISS VAN DEUSEN </b> And she sure doesn't have one now, either. She needs to live. <b> MCCULLOCH </b> I'm her legal guardian, not you or anybody else, and I alone know what's best for her. End of discussion. <b> MISS VAN DEUSEN </b> No, I think it's just the beginning. She walks past him. <b> EXT. RAMP/SHIP - ON RENNIE </b> as she reaches the top of the gangway, her heart pounding. Rennie pauses, working up the courage to look out at the lake again. <b> RENNIE'S POINT OF VIEW </b> The ROWBOAT she saw earlier is still there, even closer now. <b> RENNIE'S PUPILS </b> contract, her blood pumping faster. Then she hears a <b> FAINT VOICE BELOW HER... </b> <b> VOICE (O.S.) </b> Hhhhelp me... Rennie looks straight down at the water beneath her and sees: <b> AN EIGHT YEAR OLD BOY </b> floundering in the water. It takes us only a moment to recognize him -- IT'S YOUNG JASON. He's gasping, sucking in huge amounts of liquid, exactly like he did in the prologue. <b> YOUNG JASON </b> Hhhhelp me....I'm drowning... <b> RENNIE </b> leans back in terror, falling into Miss Van Deusen. <b> MISS VAN DEUSEN </b> What's wrong, Rennie?? Rennie frantically points over the ramp edge, unable to speak. Miss Van Deusen quickly looks and sees: <b> MISS VAN DEUSEN'S POINT OF VIEW </b> The water is calm. No Young Jason. <b> RETURN TO SHOT </b> as Rennie gets a hold of herself. <b> RENNIE </b> I just got a little dizzy. I'm fine. She continues up the ramp. HOLD on Miss Van Deusen, watching her go, somewhat troubled by it. RACK to McCulloch below her, also watching. Extremely concerned. <b> RENNIE </b> continues along the starboard side, not risking another glance overboard. She passes an older, very deranged DECK HAND, mopping the deck. HOLD on him, his bloodshot eyes following her like a crazed raven. <b> INT. BRIDGE - CLOSE ON HARPOON - DAY </b> Sharp and rusty, mounted on the wall amidst jagged scaling knives, shark jaws and other artifacts. WIDEN to reveal they are surrounding a navigational chart on the cruise ship's bridge. Admiral Robertson and his CHIEF ENGINEER are preparing for departure, checking the OMEGA satellite computer as well as the LORAN. <b> ADMIRAL ROBERTSON </b> (checking watch) Let's take in the brow. <b> CHIEF ENGINEER </b> Yes Sir. (into intercom phone.) Take in the gangway and single up all lines. SEAN and MILES enter the room; Sean gets a glance from his Dad. Miles is very impressed with the bridge. <b> SEAN </b> Hello, Dad. <b> MILES </b> Hey, Admiral Robertson. Love your ship. <b> ADMIRAL ROBERTSON </b> She's a beauty, isn't she? I should've retired from the Navy ten years ago. <b> MILES </b> You've really been generous to give us this cruise. I know I speak for everybody on board. Everybody...with the possible exception of Sean. He avoids eye contact with his father. <b> </b> <b> ADMIRAL ROBERTSON </b> Hell, there's just twenty or so of you -- we only need a skeleton crew and it's a pleasure to sail her anyway. (beat) By the way, congratulations on winning the intramural diving championships, Miles. I'm sure you made your old man proud. Admiral Robertson gives his own son a glance; maybe Sean should think about doing the same. <b> CHIEF ENGINEER </b> Have you decided on your departure protocol, Admiral? <b> ADMIRAL ROBERTSON </b> Actually, I thought I'd leave the honors to my son. <b> SEAN </b> Dad, I don't think... <b> ADMIRAL ROBERTSON </b> (to Chief Engineer, ignoring Sean) Relinquishing command of the Princess Ruby to Captain Sean Robertson. Sean has no say in the matter. Miles can feel his friend's nervousness as well. <b> ADMIRAL ROBERTSON </b> But before you take the helm, take this. He tosses Sean a wrapped box. Sean opens it. Inside is a navigational computer the size of a calculator, sitting next to a rusty old sextant. <b> ADMIRAL ROBERTSON </b> Something old and something new. I used the sextant when I was your age, but now they have these goddamn computers to do all the work for you. <b> CHIEF ENGINEER </b> (to Sean) Have you decided on a plan of departure, Captain? Sean's nervous. He eyes the Omega, quickly glancing at the LORAN, briefly referring to the navigational chart. <b> SEAN </b> How about if we start up the forward engines and come around. 180 degrees... <b> ADMIRAL ROBERTSON </b> Aren't you forgetting something? Sean looks flustered. Admiral Robertson storms to a large button, pressing it three times, piercing the air with three long blasts of the ship's horn. It underscores his frustration. <b> ADMIRAL ROBERTSON </b> We're in foggy weather! Send out the international maritime signal that a vessel is backing down, followed by a security broadcast warning other ships! He shoves the mike out at Sean, but he doesn't grab it, leaving the bridge, humiliated. There's an awkward moment for Miles, unable to find any appropriate words. He exits as well. Admiral Robertson stares out the bridge window, saddened and frustrated. It wasn't supposed to go this way. <b> EXT. DECK - ON SEAN </b> as he continues away, his retreat blocked by the DECK HAND. The crazy old man pierces a dead serious stare at Sean. <b> DECK HAND </b> This voyage is doomed. <b> SEAN </b> Yeah, tell me about it. Sean sidesteps him, moving on. <b> EXT. HARBOR - DAY (CRANE SHOT) </b> Parents and relatives wave gleefully from the docks as CAMERA RISES AND ROTATES to find eighteen or so teenagers 1ining the upper deck, happily waving back. The ship begins to slice through serene water. The voyage has begun. <b> CLOSER ON HULL </b> The water begins to ripple as the ship's speed increases. All seems normal...until JASON'S HANDS APPEAR, CLINGING TO A LOOSE MOORING LINE DRAGGING IN THE WATER. He slithers up the side towards the deck as dense fog breezes past him. <b> EXT. DECK - DAY </b> as Sean continues along, hands in pockets. He turns a corner and collides with RENNIE, walking her dog. His eyes instantly brighten, as do hers. <b> SEAN </b> Rennie... <b> RENNIE </b> Hi, Sean. <b> SEAN </b> I heard you weren't coming. <b> RENNIE </b> (glances at Toby) We changed our minds. Sean pats her dog. There's an awkward pause...they are obviously in the early stages-of a relationship. Sean reaches into his coat pocket, bringing back a small necklace-sized box. <b> SEAN </b> I got you a present. <b> RENNIE </b> But I didn't get you one... <b> SEAN </b> Forget it. It's a dumb little thing anyway. Rennie opens it up, exposing a petite silver necklace with a Statue of Liberty pendant on it. She's touched. <b> RENNIE </b> Sean...it's beautiful. Sean takes it from her, snapping it around her neck. <b> SEAN </b> I thought maybe we could hike to the top of the Statue when we got there, if you felt like it. It's supposed to be 22 stories tall. <b> RENNIE </b> I'd love to. <b> MCCULLOCH (O.S.) </b> Your father was looking for you, Mr. Robertson. McCulloch appears behind them. The mood has been broken. <b> SEAN </b> I guess I'll see you later. Sean leaves. McCulloch steps up to Rennie, pointing out to the foggy sea. Her respiration increases as she psyches herself up to look. <b> MCCULLOCH </b> There's a storm predicted tonight. Rennie looks at the ocean, forcing herself not to turn away. <b> MCCULLOCH </b> You're making a big mistake, Rennie. It's not too late to put you back on land. <b> RENNIE </b> I'm staying. <b> MCCULLOCH </b> If Miss Van Deusen knew how afraid you were of... <b> RENNIE </b> She didn't push me into coming. <b> MCCULLOCH </b> Why are you doing this to yourself? <b> RENNIE </b> I don't even know why I'm afraid, Uncle Charles. I can't even remember when it started. Don't you think it's time I found out and got over it? He takes a measured pause. <b> MCCULLOCH </b> Facing your fear doesn't always conquer it. <b> RENNIE </b> I'm staying. He's not going to change her mind. <b> P.O.V. - RENNIE AND MCCULLOCH (B & W/VIEWFINDER MATTE) </b> through a porthole window...and through the viewfinder of a video camcorder. McCulloch shakes his head, turning away from Rennie and walking away. A sinister electric guitar solo screeches out. PAN with McCulloch as he passes the window, coming around 180 degrees into a CLOSE UP of J.J. JARRETT, fingering a sleek Gibson "Flying V." <b> J.J. </b> (into camera) Is this axe awesome or what? <b> INT. J.J.'S STATEROOM - DAY </b> as J.J., a female rocker in the vein of band "Vixen," continues to wail on her guitar. She's wearing a black leather corset, with wildly teased deep red hair. Holding the camcorder is WAYNE WEBBER, MTV-acclimated, wearing the latest hip prescription glasses. <b> WAYNE </b> Too cool, J.J. Your parents came through. She pops out the guitar cable from her practice amp. <b> J.J. </b> No lie. I hear there's a big power room down below where I can get supreme concert hall echo. Come down and shoot a basement tape on me, okay? <b> WAYNE </b> Sure...but I gotta shoot some shockumentary footage first. He avoids eye contact when he says it. She gives him a look. <b> J.J. </b> Man, don't tell me you're still trying to scam on Tamara... His non-answer means yes. J.J. walks over to him, grabbing his cheeks, shaking them like jello. <b> J.J. </b> How long have we known each other? Don't be a dweeb, Wayne. She's not interested in you, only what you can do for her. She's a user. <b> WAYNE </b> She's sexy. <b> J.J. </b> So's this guitar. So what? <b> WAYNE </b> I'll catch you later. <b> </b> He exits. She mumbles something under her breath, coiling up her amp cord. <b> INT. CORRIDOR - TRACKING WITH WAYNE </b> as he walks onward. DROP DOWN to find his FEET as he passes a DARK ALCOVE...which happens to have SLIMY FOOTPRINTS AND SEAWEED leading into it. Camera FOLLOWS the footprints, RISING again and with dim recognition, our eyes fall on JASON. Lurking in the shadows. But not for long. <b> INT. POWER ROOM - DAY </b> Massive, very dark, backlit steam seeping from a maze of pipes overhead. No windows. A wall of circuit breakers and voltage meters decorate one wall, quietly humming generators on the opposite side. J.J. appears with her guitar, amp and ghetto blaster, appreciative of the surroundings. <b> J.J. </b> This place is aching for a video. Wayne, you're an asshole. She finds an outlet and plugs in her equipment. <b> JASON'S POINT OF VIEW </b> We're peering at J.J. predatorially through the steam, moving through it, behind the generators. <b> J.J. </b> pops a cassette into her blaster, jamming the "play" button. A loud rock 'n roll rhythm track blasts out. <b> JASON'S POINT OF VIEW </b> moving around the generators, eyeing her sleek leather pants as she bends over to plug in her axe. <b> TIGHT ON ELECTRIC GUITAR </b> as J.J. snaps the male end of the plug into the female. receptacle. <b> JASON'S FACE </b> appears for an instant through the vapor, then vanishes. <b> </b><b> J.J. </b> screams out the opening licks of her solo in sync with her playback. The generators are causing a breeze which makes her hair dance, steam flowing between her legs. She's lost in her music, building to a crescendo, bending the high "E" string above the upper octave fret. She opens her eyes with the pleasure of it and sees: <b> JASON </b> emerging from a cloud of vapor like her worst nightmare. <b> EXT. UPPER DECK - SAME TIME </b> as J.J.'s SCREAM echoes from an exhaust duct. WHIP PAN to find the crazed DECK HAND standing just below it, reacting with dread. He's the only one who has heard it. <b> INT. POWER ROOM - SAME TIME </b> as Jason tears the guitar off her body, raising it in the air like a hatchet. The horrified girl flees down a narrow maze of steel steps, forced back against a generator with nowhere to go. PUSH IN on her face for one last look at her before: <b> JASON </b> swings the guitar downward and buries it in J.J.'s skull. <b> EXT. UPPER DECK - SAME TIME </b> as the Deck Hand flinches upon the thick, dull sound of her demise, followed by discordant feedback from her guitar...and eventual silence. He reaches into his breast pocket, his hand shaking badly as he sips from a flask of Early Times. <b> EXT. OCEAN - NIGHT (EFX) </b> as LIGHTNING FLASHES over a gray, choppy sea. A storm is imminent. The Princess Ruby finally appears, cutting through whitecaps, no land in sight. <b> CLOSE UP - INK DIP PEN </b> as Rennie's hand carefully dips it in India ink, moving to a blank page in her journal. She hesitates for several beats. <b> INT. RENNIE'S STATEROOM - NIGHT </b> No inspiration. She puts down the pen, looking at her dog, who's curled up on the bed. <b> RENNIE </b> What do you think...time for some personal experiences to fuel our minds? The dog's eyes blink, but no more than that. <b> RENNIE </b> I agree. Rennie moves to her closet, finding a silk blouse and some black satin pants. <b> EXT. OUTSIDE DECK - SAME TIME </b> Wind is picking up, sweeping thick mist past a row of decorative flags. One of them flaps back...AND EXPOSES <b> JASON. </b> <b> THROUGH JASON'S EYES (FLYING WALL EFX) </b> as the flag whips our faces. We MOVE through it, down the empty passageway, coming to a porthole window. Rennie's window. We peer through it with unnerving intensity at the backside of Rennie as she pulls off her T-shirt, slipping on the blouse. Camera continues through the tiny round window, floating across the room, over Toby and the bed...until we're INCHES FROM THE BACK OF RENNIE'S HEAD. She suddenly spins around in fright, facing us point-blank, and: <b> REVERSE ANGLE </b> Nobody is there, her porthole window empty. But there's something surreal about the window... <b> TIGHT ON PORTHOLE WINDOW (EFX) </b> Empty grayness...then EIGHT YEAR OLD JASON FLOATS UP FROM BELOW, BUBBLES ESCAPING FROM HIS LIPS. The porthole has become a window into the depths of Crystal Lake. <b> RENNIE </b> feels her throat catch with terror and an instant later: <b> DOG TOBY </b> begins to bark vociferously, rushing to her cabin door, scratching to get out. <b> RENNIE'S EYES </b> are distracted to Toby for a second; when she looks back at the porthole, she sees: <b> AN EMPTY WINDOW </b> No water, no drowning boy. <b> RENNIE </b> snaps out of it, moving to the door, where her dog is frantically clawing with his fur up. <b> RENNIE </b> Okay Toby, calm down... She's talking to herself as much as the dog. Rennie closes the curtains on her window, then steps to her door. She swings the door open for Toby...and exposes an empty hall. Toby scrapes his way out of the room, dashing off down the hall, snarling. <b> INT. SHIP CORRIDOR - NIGHT </b> as Toby runs straight toward us. PAN with him as he rushes around a corner, leading us into a view of TAMARA and EVA, disappearing down a staircase. <b> INT. MENS GYM - DAY </b> A strong seventeen year-old black kid, JULIUS GAW, is going a few rounds with another senior boy who's clearly losing the boxing match. Julius dances around him on the mat like he's Mike Tyson, several other boys cheering them on. <b> REVERSE ANGLE - LOCKER ROOM WINDOW </b> as Tamara and Eva step into view. Eva glances around, feeling out of place in the men's locker room. <b> EVA </b> I'm not sure we're supposed to be here, Tamara. A couple of skinny boys wearing only towels walk by. But Tamara doesn't notice them, her face pressed up against the glass, watching Julius. <b> TAMARA </b> Is that a muscular bod or what? Tamara puts on a sexy smile. The other boxer sees her instead, instantly distracted. Julius lays him out with a left-right-left combination. The onlookers applaud. Julius pulls out his mouthpiece, giving Tamara a wicked smile. <b> TAMARA </b> He's undefeated, you know that? (beat) Julius is the only senior I'd even consider doing it with. If he wasn't black, that is. <b> EVA </b> (awkward) My parents are open minded about that sort of thing. <b> TAMARA </b> My stepmom couldn't care less, but Daddy would have a shit fit. (lets it slip out) He might even pay some attention to me. Tamara quickly puts up her veneer again, spotting something. <b> TAMARA </b> Gorgeous guy at ten o'clock. Look sensual. Both girls slip into instant sultry as a CREW MEMBER in his mid-twenties passes them, wearing a tool belt. Very masculine. He gives the girls a pleasant smile. Tamara turns around to check out his back side. <b> TAMARA </b> I think it's time for some recreational activity, girl. <b> EVA </b> Sounds good. I hear there's a shuffleboard court on deck -- it might be kinds cool... <b> TAMARA </b> You're joking, right? She wasn't, but Eva tries to act like she was. Tamara walks on, Eva following. <b> INT. STATEROOM HALLWAY - NIGHT </b> as McCulloch steps from Rennie's room, looking very worried. Wayne Webber passes by, his eye stuck in his viewfinder. McCulloch yanks the camcorder away from his face. <b> MCCULLOCH </b> Have you seen my niece anywhere? <b> WAYNE </b> Yeah, motivating downstairs, I think. What's the problem, Mr. McCulloch? <b> MCCULLOCH </b> Senior predictions started five minutes ago and she hasn't shown up. <b> WAYNE </b> Some of us don't want our futures predicted. <b> MCCULLOCH </b> In your case I'm sure that's true. He brushes past Wayne angrily. <b> INT. SERVICE AREA - NIGHT </b> as Tamara drags Eva into a secluded service area, pulling out her mirror, straw and baggie. <b> TAMARA </b> The night time is the right time. Tamara hands the straw to Eva. <b> EVA </b> (nervous) No thanks. <b> TAMARA </b> What? Don't be a lightweight...this is top dollar toot. <b> EVA </b> It's not that, it's just that... (beat) It I get caught, I'll lose my science scholarship and everything. <b> TAMARA </b> You're talking to the prom queen, Eva. Do you really think I'm going to risk getting caught? <b> EVA </b> (a pause) I guess not. <b> TAMARA </b> Do you realize how many people would kill to be sitting here right now? Come on, it's grad night. You've got your whole life to be uptight. Eva takes the straw. <b> STALKING POINT OF VIEW </b> as we move down the corridor, in and out of shadows, hearing giggles from Tamara and Eva up ahead. Jason's coming... <b> ANGLE - TAMARA AND EVA </b> as Eva takes a nosefull, sneezing badly. <b> TAMARA </b> Is that unbelievable or what? Tamara giggles, getting ready to tap out another line. But the snickering stops upon the sound of APPROACHING FOOTSTEPS. They both look up, every muscle tensing with fear as: <b> RENNIE </b> appears from the shadows, just as startled to see them. It's not Jason at all. Rennie can't help noticing the cocaine, trying hard to ignore it. <b> TAMARA </b> Jesus, you scared the hell out of us. <b> RENNIE </b> Have you seen my dog? I think he came this way. <b> TAMARA </b> No, we haven't. (awkwardly) Care for a hit? <b> RENNIE </b> No thanks. Rennie continues on. After she's gone... <b> TAMARA </b> A real space cadet. I wonder if she'll narc on us... <b> EVA </b> I have her in Creative Writing and she's fairly nice. <b> TAMARA </b> Nobody related to McCulloch can be nice. Tamara puts the straw to her nose. <b> ANGLE - RENNIE </b> as she presses on, the corridor getting darker. <b> RENNIE </b> Toby? No reply. She walks on, turning down the left hallway... but camera turns down the right hallway. Suddenly JASON REVEALS HIMSELF, quietly stepping from the GAME ROOM. He's holding a pool cue, which he proceeds to snap in half, providing a splintery sharp shaft. <b> INT. SERVICE AREA - SAME TIME </b> as Tamara finishes off her line, wiping her nose with a sniffle. <b> TAMARA </b> Oh yeah. Ready to party and then some. She rolls up her baggie, stuffing it into her purse. <b> STALKING POINT OF VIEW </b> as we come down a corridor, turning into the Service Area, stomping right up to Tamara and Eva. They both GASP; Tamara drops her mirror, which SHATTERS on the ground. <b> REVERSE ANGLE </b> They are facing McCulloch. <b> MCCULLOCH </b> What are you doing in here? <b> TAMARA </b> Nothing. He eyes the broken mirror. He wasn't born yesterday. <b> MCCULLOCH </b> Are you girls using drugs? <b> EVA </b> Do you think I would use drugs, Mr. McCulloch? We were just exploring the ship. He doesn't want to believe Eva is a druggie. But Tamara is a different matter. He levels his eyes on her. <b> MCCULLOCH </b> I'11 be coming around your stateroom in exactly fifteen minutes, Miss Mason. You'd better have your biology project ready or I'm phoning your parents. <b> TAMARA </b> They're out of town. <b> MCCULLOCH </b> Then I'll make sure you remain on board while your classmates see the sights. He's gotten to her with that one. McCulloch storms away. <b> EVA </b> What are you going to do? <b> TAMARA </b> Relax, I've got McCulloch covered... but that little narcing bitch niece of his is a different matter. (calculating) Rumor has it she's a teensy bit afraid of the water... <b> SPLASH! </b> as a body pierces the surface of the deck swimming pool. It's MILES, having just completed a dive from the high board. Miss Van Deusen and several others stand at poolside, giving him some applause. <b> MISS VAN DEUSEN </b> Poetry in motion, Miles. <b> MILES </b> A half-twist short. I'll hone that dive yet. He swims to the side, leading us to a view of Rennie. She's very cautious about getting too close to the pool edge as she approaches Miss Van Deusen. <b> MISS VAN DEUSEN </b> Rennie -- I was just on my way over to your room <b> RENNIE </b> Have you seen my dog anywhere? <b> MISS VAN DEUSEN </b> No, but I'm sure Toby's fine. The ship's only so big and there's certainly no way off it, is there? She smiles reassuringly, but her words are less than comforting. <b> INT. SHIP CORRIDOR - TRACKING WITH TOBY - SAME TIME </b> as the canine continues to sniff out Jason through the maze of corridors. TRACK with the dog as he slows his pace, knowing he's getting close to something. <b> TOBY'S POINT OF VIEW (STEADICAM) </b> Low to the ground, creeping past a steam vent which obscures his vision, then turning down a metal staircase, weaving into another passageway. Then with absolutely no warning, A BODY FALLS FROM ABOVE, THUDDING DIRECTLY IN <b> FRONT OF US. </b> <b> TOBY </b> rears back with teeth bared, but: <b> THE BODY </b> is quite dead: Toby is snarling at the corpse of the TEENAGE BOXER who lost his bout against Julius. He's still in his boxing shorts...BUT JASON'S SPLINTERY POOL <b> CUE HAS BEEN STABBED THROUGH HIS CHEST. </b> <b> EXT. DECK POOL - ON RENNIE AND MISS VAN DEUSEN </b> as they walk along the edge of the pool. <b> MISS VAN DEUSEN </b> So, are you having fun yet? <b> RENNIE </b> (lying) Yeah...a lot. <b> MISS VAN DEUSEN </b> I seem to detect a hint of ingenuousness in your tone. (beat) In other words, level with me. <b> RENNIE </b> (a pause) There's something I haven't told you... ...But before she can begin the next sentence, Rennie is shoved from behind. <b> </b> <b> WATER ANGLE </b> as she SPLASHES INTO THE POOL'S DEEP END. <b> MISS VAN DEUSEN </b> spins around, seeing Tamara standing there with Eva. <b> TAMARA </b> Wow, sorry... <b> RENNIE </b> flounders at the surface, nobody realizing the terror she's experiencing. She's too scared to even cry for help. <b> MISS VAN DEUSEN </b> isn't looking at Rennie, her attention on admonishing Tamara. <b> MISS VAN DEUSEN </b> Why on earth would you do something like that? <b> TAMARA </b> It was an accident, I swear... Eva avoids eye contact, feeling awful. Sean comes walking up, seeing Rennie. <b> SEAN </b> What happened? (to Rennie) Rennie, are you okay? <b> RENNIE'S POINT OF VIEW </b> She's can't even hear Sean, her vision being splashed by the chlorinated water. She sinks under the surface, turning around...AND COMING FACE TO FACE WITH YOUNG JASON. The eight year-old corpse GRABS HER ANKLE AND <b> TRIES TO DRAG HER DOWN. </b> <b> SEAN'S POINT OF VIEW </b> as Rennie sinks under the surface, all alone, thrashing in terror. <b> SEAN </b> realizes she's in trouble. He immediately dives in after her, pulling her to the pool's edge, where Miss Van Deusen helps to lift her out. <b> TAMARA AND EVA </b> quickly move on. <b> TAMARA </b> That was truly excellent. <b> EVA </b> (feels like shit) Yeah. <b> TAMARA </b> Time to check out the waiters. <b> EVA </b> I think I'll pass. See you later, okay? <b> TAMARA </b> But...wait a minute! Eva walks away. Tamara acts angry, but deep down she's hurt. <b> TAMARA </b> Some friend you are. <b> EXT. POOL SIDE - SAME TIME </b> as Sean climbs from the pool to join Miss Van Deusen, who is trying to comfort Rennie. <b> MISS VAN DEUSEN </b> (to Sean) Bring her a towel, okay? Sean nods, hurrying off as others start to crowd around. Miss Van Deusen looks up at them. <b> MISS VAN DEUSEN </b> She's fine -- everybody go back to what you were doing. They disperse. Rennie slowly starts to cry, holding tight to her teacher. <b> MISS VAN DEUSEN </b> Care to talk about it? After a moment to compose herself... <b> RENNIE </b> I can't swim. <b> MISS VAN DEUSEN </b> I gathered that. Rennie says nothing else. Miss Van Deusen knows she's holding out. <b> MISS VAN DEUSEN </b> I had a skiing accident in high school, broke my left leg. It took three winters before I would even look at the snow again...but the solution kept eluding me. (beat) I finally took lessons. I've never broken a bone since. <b> RENNIE </b> It's not that simple. <b> MISS VAN DEUSEN </b> Maybe not. But you're not telling me everything, are you? <b> RENNIE </b> (long pause) Whenever I get near the water, I see this young boy drowning. He tries to pull me down with him. The teacher didn't expect this, taking a thoughtful pause. <b> MISS VAN DEUSEN </b> When did this start? <b> RENNIE </b> About four years ago...at Crystal Lake. I spent a few summers there with Uncle Charles inbetween boarding school. <b> MISS VAN DEUSEN </b> After your parents passed away? Rennie nods somberly. <b> MISS VAN DEUSEN </b> Did you have an accident in the lake? <b> RENNIE </b> No. It was just a normal summer. I've never been able to figure it out. <b> MISS VAN DEUSEN </b> Only one young boy ever drowned in that lake, and that was before you were even born. His name was Jason Voorhees. The name has triggered some deep memory...but the recollection vanishes upon the sound of her uncle's voice. <b> MCCULLOCH (O.S.) </b> Dear God... <b> ANOTHER ANGLE </b> as McCulloch rushes over to Rennie, seeing that she's soaked. He's livid. <b> MISS VAN DEUSEN </b> She's fine, Charles. Take it easy... <b> MCCULLOCH </b> Oh, I can see that. You've done a wonderful job of supervising the kids, Miss Van Deusen. <b> RENNIE </b> It wasn't her fault. He gets Rennie to her feet just as Sean runs back with a towel. McCulloch grabs it from him, wrapping it around his niece, facing both Miss Van Deusen and Sean. <b> MCCULLOCH </b> Stay away from her...both of you. He starts to lead her away. The crazy DECK HAND blocks their path, slipping his flask away. <b> DECK HAND </b> He's come back and you're all going to die. Rennie gazes at the Deck Hand, then back at McCulloch. <b> RENNIE </b> Just...leave me alone... She pulls away from him, hurrying off, confused and frightened. McCulloch's retinas pierce the Deck Hand with scorn. He checks his watch, then storms off. <b> INT. TAMARA'S STATEROOM - NIGHT </b> as a loud, firm KNOCK punctuates the silence. Then comes a sultry voice... <b> TAMARA (O.S.) </b> The door's open. McCulloch swings it open. <b> MCCULLOCH </b> I'm in no mood for any more stall tactics, Miss Mason. Where is your final project? <b> REVERSE ANGLE </b> as Tamara fills a pair of champagne glasses with a bottle of Dom Perignon. She's wearing a full body robe. <b> TAMARA </b> Wouldn't you like a glass of champagne first, Charles? He's about to lose his temper. McCulloch steps closer. <b> MCCULLOCH </b> Where did you get that alcohol? <b> TAMARA </b> I packed it. Just for us. <b> EXT. DECK CORRIDOR - STALKING POINT OF VIEW </b> as we approach Tamara's porthole window, peering through it. We can't hear the words but we can clearly see the people. <b> INT. TAMARA'S STATEROOM - CONTINUOUS </b> as McCulloch takes the bottle from her, setting it down on her nightstand. <b> MCCULLOCH </b> That's it. You're not setting foot off this ship until we return home. <b> TAMARA </b> But I haven't even shown you my biology project... Tamara unties her robe. PAN DOWN to the floor with it as it softly piles at her bare feet. <b> ANGLE - PORTHOLE WINDOW </b> as the SHADOW OUTSIDE quickly blurs past the window. <b> RETURN TO SCENE </b> McCulloch is flabbergasted, too stunned to fully react. Tamara is wearing a layered teddy, which she's beginning to unsnap, exposing her lithe body...but that's not all. Tamara has drawn all her major organs on her bare skin. <b> TAMARA </b> Take a closer look, Charles. I want to make sure I labeled all my organs correctly. <b> EXT. TAMARA'S STATEROOM - STALKING POINT OF VIEW </b> as we approach her door, still cracked open from McCulloch's entrance. We get there just in time to see Tamara slip her arms around McCulloch, planting her lips on his, pressing her nubile flesh up against his stiffly starched shirt. <b> INT. TAMARA'S STATEROOM - CONTINUOUS </b> as she holds him tight. He finally breaks away in a fit of anger. <b> MCCULLOCH </b> Oh, you've done it now. Not only are you going home, I'll see to it that you spend next year back in a high school classroom! He storms for the door, swinging it open, coming face to face with: <b> WAYNE </b> who casually lowers his camcorder. <b> TAMARA </b> I don't think so, Mr. McCulloch. (to Wayne) Did you get anything good? His eyes are unable to leave her nakedness. <b> WAYNE </b> Oh yeah. She quickly slips on her robe again, all business. McCulloch realizes what has just transpired. <b> MCCULLOCH </b> You'll never get away with it. (eyeing Wayne) And you can forget about ever attending any film school. (serious beat) You're both going to be very, very sorry. He storms off. Wayne looks very, very nervous. Tamara steps over to him, cuddling up. <b> TAMARA </b> Relax, Wayne. He won't risk doing a thing. (beat) Can I have the tape? He pops the eject button, absently handing it over. Wayne steps into her room, nervous and excited to be there. He lifts the glass of champagne she poured for McCulloch. <b> WAYNE </b> This is going to sound supremely lame...but I've had the major hots for you since our sophomore year, Tamara. He gulps down the fizz. She forces a smile, stashing the incriminating videotape. <b> TAMARA </b> That's sweet, Wayne. Look, I'd love to chat but I'm really pressed for time. (ushering him to door) Let's try to get together later, okey- doke? <b> WAYNE </b> But I thought... <b> TAMARA </b> Thanks for the camerawork. And out he goes, the door shut in his face. Wayne stands outside her room, realizing he's a major chump. <b> WAYNE </b> Wayne, you're an asshole. He despondently exits. <b> INT. TAMARA'S STATEROOM - SAME TIME (STEADICAM) </b> as Tamara heads for the bathroom, slipping off her robe. She moves to the shower curtain and we're right behind her. Her hand reaches up, grabbing the curtain, yanking it back... Nothing is there. <b> INT. LADIES RESTROOM - SAME TIME - NIGHT (EFX) </b> as Rennie enters, her eyes reddened. She moves to the sink, looking at herself in the mirror. So much for the silk blouse and satin pants, not to mention her soaked hair. Rennie runs some warm water, rinsing her face. When she starts to fill her hands a second time, BLOOD POURS OUT THE FAUCET INSTEAD OF WATER. Rennie gasps, jerking up and seeing YOUNG JASON REFLECTED ON THE OTHER <b> SIDE OF THE MIRROR, SPLASHING IN WATER. </b> <b> RENNIE </b> It's not real, it's not real... <b> INT. TAMARA'S SHOWER - SAME TIME </b> as water from the shower head SPLASHES CAMERA for a beat before Tamara turns it off. <b> ANOTHER ANGLE </b> as Tamara reaches for her robe, slipping it on. Her body paint has been washed off. She steps from the shower, glancing in her vanity mirror AND SEEING THE REAL JASON REFLECTED IN IT. Tamara spins around, looking face to face with JASON IN HER BATHROOM. Just as she SCREAMS: <b> INT. LADIES RESTROOM - SAME TIME (EFX) </b> Young Jason reaches out to grab Rennie, HIS FIST CRASHING THROUGH THE MIRROR. Right when Rennie SCREAMS: <b> INT. TAMARA'S BATHROOM - SAME TIME </b> The real Jason SHATTERS TAMARA'S VANITY MIRROR WITH HIS FIST. He grabs a sharp chunk of it, advancing on a whimpering Tamara. <b> TAMARA </b> Please...please don't... Jason raises the shard above her and just as she <b> SHRIEKS... </b> <b> CLOSE UP - STEAM WHISTLE OF SHIP </b> as it blasts loudly in the bleak stormy night. It begins to rain. <b> EXT. LADIES RESTROOM - NIGHT </b> as Rennie comes rushing out, right into the arms of. Sean. She clings to him, sobbing as the rain falls over them. <b> SEAN </b> It's okay...you're going to be okay. <b> RENNIE </b> I want to go home. I want off this ship. After a moment... <b> SEAN </b> Me too. (beat) Let's go talk to my Dad. He puts his arm around her, leading her toward the bridge. <b> INT. BRIDGE - NIGHT </b> as wind and rain pummel the bridge window.. Admiral Robertson turns to his Chief Engineer. <b> ADMIRAL ROBERTSON </b> Let's kick in the stablilizers, Mr. Carlson, and get the seas off the quarter. These kids are in for one hell of a storm. <b> CHIEF ENGINEER </b> Yes Sir. Activating comfort cruise mode. The Chief Engineer moves to a bank of toggle switches, flipping a row of them. <b> TIGHT ON NAVIGATIONAL CHART WALL - SAME TIME </b> as a bloodstained HAND silently removes the rusty harpoon hanging above the map. <b> ADMIRAL ROBERTSON </b> gets a reflective look in his weary eyes. <b> ADMIRAL-ROBERTSON </b> How olds your boy now, Carlson? <b> CHIEF ENGINEER </b> Nineteen months. <b> ADMIRAL ROBERTSON </b> A tremendous age. Take some advice from a salty old man: don't push him too hard. The Chief Engineer nods with a sympathetic smile as the Admiral steps off the bridge, onto the stormy deck, contemplating the sea. The Chief Engineer moves to the radio/intercom console. He lifts a telephone, punching in a three digit number. PUSH IN TIGHT ON HIS FACE. <b> CHIEF ENGINEER </b> This is the bridge. Approaching weather suggests we secure the main deck and... His sentence is sharply cut off, his head jerking from excruciating, instant pain. His mouth contorts with words no one will ever hear as he stares into the face of: <b> JASON </b> holding the opposite end of the harpoon. He shoves it forward with one more staccato jerk and: <b> CLOSE UP - CHIEF ENGINEER'S BACK </b> -- The harpoon's bloody, corroded tip pierces through his once-white uniform. <b> ADMIRAL ROBERTSON </b> returns to the bridge as LIGHTNING flashes outside. <b> ADMIRAL ROBERTSON </b> Better have them doublecheck the lifeboat stations as well... Admiral Robertson stops cold upon the sight of Mr. Carlson. He hurries over to him, kneeling down, freezing as a pair of MUDDY FEET ENTER FRAME. Admiral Robertson bends his neck upwards to face: <b> JASON </b> hovering over him, now clutching one of the scaling knives. <b> INT. BRIDGE CORRIDOR - NIGHT </b> as Sean and Rennie walk up the corridor leading to the bridge. <b> RENNIE </b> Can he really take us home? <b> SEAN </b> Not completing a voyage is against everything he stands for. But I think I can convince him to call a Coast Guard cutter for you. <b> RENNIE </b> What about you? <b> SEAN </b> If I go with you, he'll never speak to me again. (beat) But I'm never going to live up to his expectations anyway...so maybe it's the right thing to do. He's made a big decision. Sean takes her hand as they walk on. <b> THEIR POINT OF VIEW </b> moving closer and closer to the bridge door, having not the slightest inclination of what's in store for them. <b> SEAN </b> knocks on the bridge door. No answer. He's confused. He pushes the door open but something is blocking it. Sean puts his weight into it, shoving hard. <b> INT. BRIDGE </b> as the door slides open, Sean stepping inside. His eyes roil downwards upon seeing THE DEAD CHIEF ENGINEER, THE <b> HARPOON PROTRUDING FROM HIS BLOODY CHEST. </b> <b> SEAN </b> Oh Jesus...Dad?? Sean looks over at the helm...where his father is still sitting in the swivel chair, his back to them. Silent. Sean sidesteps the Chief Engineer's corpse, moving toward his father as Rennie remains frozen in shock. <b> SEAN'S POINT OF VIEW </b> Slowly walking toward Admiral Robertson...at least he thinks it's his dad because he's unable to see his face. Is it Jason now wearing the uniform?? When he's about two feet away from him... <b> SEAN </b> reaches out and swivels the chair around. It is his father BUT HIS THROAT HAS BEEN SLIT. Sean staggers backwards, uncomprehending, his senses overloaded. We MOVE with him until he's backed into Rennie, clutching onto him tightly. <b> SEAN </b> He's...he's dead... <b> INT. CORRIDOR OUTSIDE RENNIE'S STATEROOM - SAME TIME </b> as Miss Van Deusen steps up to Rennie's door, gently knocking. <b> MISS VAN DEUSEN </b> Ronnie? I just came by to see how you were feeling... No answer. She knocks harder...and it creaks open, unlocked. <b> MISS VAN DEUSEN </b> Rennie...? Suddenly the door is jerked from her grasp and swung open. MCCULLOCH is standing on the other side of it. <b> MCCULLOCH </b> I thought I told you to stay away from her. <b> MISS VAN DEUSEN </b> (holds her ground) Where is she? <b> MCCULLOCB </b> (accusing) That's a very good question and I'd appreciate an answer. A LOUD BUZZER blares out of an intercom speaker next to their heads, causing the teachers to both jump. Sean's unsteady voice immediately follows. <b> SEAN (V.O.) </b> Attention everybody, attention. This is Sean Robertson... <b> EXT. SWIMMING POOL - SAME TIME </b> Miles is toweling off under the shelter of a gazebo as Sean's voice blares out of a rain-pounded megaphone speaker nearby. <b> SEAN (V.O.) </b> There's been... (swallows) What I mean is, this is an emergency... Miles knows he can't be joking around. Wayne comes walking by, covering his camcorder with his jacket. <b> WAYNE </b> Miles -- have you seen J.J.? She was supposed to be jamming down in the power room but... Miles gestures for him to be quiet, listening very worriedly. <b> SEAN (V.O.) </b> Repeat, this is an emergency... <b> INT. GYM LOCKERS - SAME TIME </b> as JULIUS and two other senior boys finish dressing after a shower, hearing Sean's words reverberate around them. <b> SEAN (V.O.) </b> I want everybody to meet on the bridge... <b> JULIUS </b> What the fuck is this? The others shrug, concerned. <b> EXT. SHUFFLEBOARD COURT - SAME TIME </b> The wooden shuffleboard disks are drowning in precipitation. Eva stands alone in the rain, staring at the court as Sean's voice continues. <b> SEAN (V.O.) </b> Stay calm, but get here as quick as possible. Walk with a friend if you can... Eva wipes the rain from her face, then walks away. <b> INT. BRIDGE - ON SEAN </b> trying his best to keep it together. He glances at his dead father, still unable to believe it. <b> SEAN (V.O.) </b> God, I wish this was a joke, but it's not. Sean slowly puts down the phone. He's lost in a daze. Suddenly the SHIP LURCHES, a huge swell SPLASHING THE BRIDGE WINDOW. Admiral Robertson's body falls from the swivel chair. <b> RENNIE </b> What is happening??? Sean regains his balance, moving to the computer console, looking at the OMEGA and LORAN like he's never seen them before. <b> SEAN </b> I don't know...we've gone off course or something... <b> RENNIE </b> What do you mean??? Another wave hammers the bow. She's in a state of awful panic. <b> SEAN </b> I don't know what I mean! All's I know is that there's no one guiding this ship anymore... Sean is starting to lose it. The fear of the ocean guiding her, Rennie rushes to him, gripping and shaking him. <b> RENNIE </b> Can't you call for help?? Sean tries to get a grip and assess the situation, pacing frenetically. <b> SEAN </b> I think so. But we have to lower the anchors so we don't drift any further... <b> RENNIE </b> Where are they? <b> SEAN </b> The bow...front of the ship. There's a hoist on each side that lowers them She starts to exit. <b> SEAN </b> I didn't mean for you to go! <b> RENNIE </b> Just radio for help, okay??? She hurries out the door, working on terror-induced adrenaline. Sean rushes to the radio console, depressing the keying button, speaking into the mike. <b> SEAN </b> Mayday, mayday, mayday... <b> ANOTHER ANGLE </b> as JULIUS arrives with the others from the locker room. They react to the dead bodies while Sean continues at the radio. <b> SEAN </b> Please...can anybody out there hear me?? No response. WAYNE and MILES rush in. <b> MILES </b> Sean, what's going on? Then he sees the corpses. He needs no further answer. <b> WAYNE </b> Jesus Christ... He's too scared to even videotape it. Sean is bombarded with questions as he tries to figure out the radio. <b> JULIUS </b> Who did this, man? <b> WAYNE </b> Is the radio even working?? <b> MILES </b> Isn't there some international S.O.S. thing you can do??? <b> SEAN </b> (suddenly remembers) Channel 16...the distress frequency... (dialing knob) Mayday, mayday, mayday...this is the Princess Ruby. Please, somebody answer... <b> EXT. OCEAN - NIGHT (STOCK) </b> as a COAST GUARD CUTTER tracks through stormy seas. <b> RADIO OFFICER (V.O.) </b> This is Coast Guard cutter Dallas. What is the nature of your problem, Ruby? <b> INT. BRIDGE - ON SEAN AND OTHERS </b> as they hear the voice, reacting, relieved and thrilled. <b> SEAN </b> The Captain and Chief Engineer... they've been...they're dead. <b> RADIO OFFICER (FILTERED V.O.) </b> (a grave-pause) What is your location? <b> SEAN </b> I...I don't know... <b> RADIO OFFICER (FILTERED V.O.) </b> Is your ship equipped with Omega satellite navigation or LORAN? <b> SEAN </b> Yes... <b> RADIO OFFICER (FILTERED V.O.) </b> The LORAN has a digital printout of your latitude and longitude. Give me the coordinates and we'll be there as quick as we can. Sean hurries to the LORAN, reading the numbers. <b> EXT. DECK - RADIO ANTENNA - SAME TIME (EFX) </b> as LIGHTNING STRIKES above it in the night sky. Camera slowly ADJUSTS to find the RADIO ANTENNA CABLE. A second later, JASON'S HAND REACHES FOR IT, GETTING A FIRM GRASP. <b> INT. BRIDGE - SAME TIME </b> as Sean hurries back to the radio, pressing it against his spitless mouth. <b> SEAN </b> I've got the numbers. <b> RADIO OFFICER (FILTERED V.O.) </b> Give me the degrees first, followed by minutes and sec... Suddenly his voice is CUT OFF, followed by STATIC. <b> SEAN </b> Hello? Are you there?? No response. A lump sinks into everyone's throat. <b> EXT. DECK - RADIO ANTENNA </b> as Jason drops the cable he's just torn out, marching onward. <b> EXT. BRIDGE - NIGHT </b> as McCulloch bursts onto the bridge, followed by Miss Van Deusen. <b> MCCULLOCH </b> I demand to know what is going on... <b> MISS VAN DEUSEN </b> Oh dear God... She's seen the bodies. McCulloch follows her glance, paling. He quickly takes charge, pushing through the students. <b> MCCULLOCH </b> Where's the radio? <b> SEAN </b> It's...dead. <b> DECK HAND (O.S.) </b> You're all going to die. All heads spin as the deranged DECK HAND treads out from a shadowy corridor. <b> DECK HAND </b> You're the last ones. He's come back for you. <b> MCCULLOCH </b> What are you talking about? The Deck Hand takes a final swig from his flask, dropping it with unsteady hands. <b> DECK HAND </b> Jason Voorhees. There is a collective, disconcerting silence triggered by the infamous name. <b> MCCULLOCH </b> You're insane, old man. Jason Voorhees has been dead for over thirty years. <b> DECK HAND </b> He walks this ship, here and now. <b> MCCULLOCH </b> A killer walks this ship indeed. And it's certainly none of us... The crazed old man gets his drift. Everyone looks at him suspiciously. McCulloch grabs a SCALING KNIFE off the wall, taking a step towards him. <b> DECK HAND </b> You're the one who's insane!! The raving man flees back the way he came. McCulloch raises the flare gun; Miss Van Deusen grabs McCulloch's arm, stopping him. <b> MISS VAN DEUSEN </b> What are you doing?? <b> MCCULLOCH </b> That lunatic has been spouting off about Jason since we boarded... (eyeing bodies) It's no coincidence. <b> MISS VAN DEUSEN </b> But that doesn't prove that he's the one! <b> MCCULLOCH </b> Walking corpses are not real! <b> JULIUS </b> Yeah, well these dead bodies are sure enough real. (to the others) I say we regroup and find this motherfucker before he finds us. There's a murmur; it makes sense. <b> MCCULLOCH </b> You'll do no.such thing and watch your mouth, young man! I'm in charge here! They all look at McCulloch defiantly. <b> JULIUS </b> School's out, McCulloch. (to the others) Let's go. Julius walks off the bridge; all the seniors follow except Sean. <b> MISS VAN DEUSEN </b> Please everybody, stay here!! They don't listen. McCulloch starts to go after them...and then it hits him: <b> MCCULLOCH </b> Christ...where's Rennie?? <b> SEAN </b> She's...she's dropping the anchors. I thought the Coast Guard could find us easier if... <b> MCCULLOCH </b> What?? You sent her out there with a murderer running around loose?? <b> EXT. DECK - NIGHT </b> as Rennie moves past wet, empty lounge chairs towards the bow. She passes a row of translucent windows. The first three are normal...but the fourth has the SILHOUETTE OF <b> JASON ON ITS OPPOSITE SIDE. </b> He begins to stride parallel to her, then disappears when the windows end and a wall takes over. <b> INT. BRIDGE CORRIDOR - NIGHT </b> as Julius and his followers continue on, passing Eva, who's coming up from a staircase. She stops Wayne. <b> EVA </b> What's going on? I heard on the P.A. system that... <b> WAYNE </b> (interrupting) The Captain's been murdered. The buzz is that Jason might be on board. <b> EVA </b> Jason...Voorhees? She knows the legend as weld as everybody else. Wayne nods gravely, moving to catch up with the others. Eva rushes up to him again. <b> EVA </b> Have you seen Tamara? <b> WAYNE </b> No. And I'm not losing any sleep over it. <b> EVA </b> But she might be in trouble... <b> WAYNE </b> So what else is new? (beat) Look Eva, you're asking the wrong dude to feel sorry for Tamara Mason. Wise up -- it's not hip to be her friend. <b> EVA </b> I don't care about being hip anymore. She means it. Wayne nods with understanding. <b> WAYNE </b> I'm sorry, but I've gotta find J.J. He hurries on. <b> EXT. BOW - NIGHT </b> as Rennie appears, fighting the wind and rain to get closer to the anchor hoists. <b> POINT OF VIEW THROUGH DECK WINDOW - SAME TIME </b> --spying on Rennie like a wolf watching a lamb. We MOVE a few windows down, getting a better view of her. <b> REVERSE ANGLE - ON JASON </b> deciding that the time is right to strike. His hand moves to the bow entrance door knob, slowly turning it, pulling it open. <b> EXT. BOW - ON RENNIE </b> moving closer to the right anchor hoist, her back to us as well as Jason. She climbs behind the hoist, looking at the consoles. Then suddenly a BARK. <b> RENNIE </b> Toby? She turns, catching a glimpse of her dog running down the side of the deck. Rennie leaves the hoist, going after Toby. <b> JASON'S POINT OF VIEW </b> through the crack in the door, watching Rennie unexpectedly take off. He's about to move after her when ha hears: <b> EVA (O.S.) </b> Tamara? Are you around here anywhere? Jason quietly closes the door. Rennie will have to wait. <b> INT. CORRIDOR - TRACKING WITH EVA </b> as she cautiously walks along, poking her head in every alcove. <b> EVA </b> Tamara? <b> JASON'S POINT OF VIEW </b> moving down the same corridor, catching a glimpse of Eva before she turns a corner and disappears. <b> INT. HALLWAY/TAMARA'S STATEROOM - MOVING WITH EVA </b><b> (STEADICAM) </b> Eva steps into the hallway outside Tamara's stateroom. She walks up to Tamara's door, knocking on it. It swings open, unlocked. <b> EVA </b> Tamara? (no response) I just want to talk with you. She steps into Tamara's room and we go in with her. The quarters are empty. Eva stands there for a beat, confused and scared. She's about to leave when a CREAKING SOUND causes her to look back at: <b> THE BATHROOM DOOR </b> It slowly swings open...splashing Eva's eyes with grotesque multi-images of Tamara: SHE IS HANGING ON THE <b> DOOR HOOK, HER BODY PIN-CUSHIONED WITH A DOZEN MIRROR </b><b> SRARDS. </b> <b> EVA </b> shrieks, running back out the door... <b> INT. STATEROOM HALLWAY </b> ...and sliding to a abrupt halt because JASON IS STANDING AT THE END OF THE HALLWAY. He moves toward Eva like a bulldozer. She turns a rapid 180 and sprints in retreat. <b> RUNNING WITH EVA (HAND HELD) </b> Gasping for oxygen, Eva has no time to even scream as she flees from the monster, erratically turning down a spiral staircase and running on. <b> JASON'S POINT OF VIEW (STEADICAM) </b> chasing after her with the smooth determination of a shark, never letting her get too far in the lead. <b> INT. BOWELS OF SHIP - ON EVA </b> Empty for a second, then Eva appears, weaving her way through a maze of corridors and passageways. She races past a sign directing passengers to "CLUB RUBY." <b> ANGLE - JASON </b> --entering the same corridor a beat after Eva exits it in the direction of the disco. He tramples onward. <b> INT. CORRIDOR/DISCO (STEADICAM) </b> The thudding low frequency of a mesmerizing dance tune precedes Eva as she tears open a door, entering the corridor. MOVE BACKWARDS WITH HER as she rushes forward, curving through the shallow passageway and emptying out onto a high tech DISCO FLOOR. A flashing Star Wars lighting system assaults her all directions along with the music. She's all alone in here. <b> TIGHT ON EVA </b> The lights strobing across her face only accentuate her terror. She spots another door on a small stage, rushing to it. It's locked. <b> CROOKED ANGLE - ENTRANCE DOOR </b> as Jason enters the corridor, SLAMMING THE DOOR SHUT <b> BEHIND HIM. </b> <b> EVA </b> decides this is the wrong place to be. She moves for the corridor again and: <b> JASON </b> appears on the corridor steps for a brief second. The spotlight goes black, then flashes on again. Now he's gone. <b> EVA </b> backs away, sliding along the edge of the dance floor like she's on a building ledge. Chaser lights and mirror balls fondle her body as she moves as far away from the point where she last saw him. But: <b> JASON </b> illuminates only ten feet from her, a crimson strobe assaulting his hockey mask. She's on a collision course with him. <b> EVA </b> whirls dizzily to the center of the dance floor upon the sight of him. Camera SPINS with her in 360 degree arcs, PUSHING IN on her face. <b> EVA'S POINT OF VIEW </b> spiraling counter-clockwise on the dance floor, flashes of Jason materializing where she least expects to see him. And getting closer. Finally at the point of exhaustion: <b> EVA </b> stops, looking everywhere. <b> EVA'S POINT OF VIEW </b> He seems to be gone. She catches her breath...then sensing his presence, she revolves a half-turn to face: <b> THE HOCKEY MASK </b> exploding under a pin spotlight, standing directly before her. His forearms recoil with lightning speed as he grips her throat... <b> WIDE SHOT - DISCO </b> Thundering music. Frantic lights. And Jason and Eva at the center of it all. HER FEET ARE TWENTY-FOUR INCHES OFF <b> THE GROUND, KICKING MADLY AS THE LIFE IS BEING CHOKED OUT </b> OF HER. Finally Eva's legs go rag doll limp. Jason flings her to the ground like a sack of flour. This dance is over. <b> EXT. DECK - NIGHT </b> Rennie appears again, scanning her no-visibility surroundings. <b> RENNIE </b> Toby? Where'd you go? No sign of her dog. She remembers her mission, heading to the anchors again. <b> EXT. BOW - CONTINUOUS </b> as Rennie arrives on the bow, climbing into the left hoist box behind the huge anchor cable. <b> STALKING POINT OF VIEW </b> moving up to the bow door like Jason did before, cracking it open, seeing Rennie from behind. And moving towards her. <b> RENNIE </b> is oblivious as she reads the directions above the controls. <b> INSERT - HOIST LEVER (SECOND UNIT) </b> as Rennie's hand grabs it, shoving it forward. <b> INSERT - GREEN HOIST BUTTON (SECOND UNIT) </b> A moment later, her thumb finds it and depresses it. <b> INSERT - ANCHOR CHAIN (SECOND UNIT) </b> as the massive black chain links thunder to life. <b> STALKING POINT OF VIEW </b> He's now within ten feet of the unaware girl. <b> RENNIE </b> remains in the hoist box, making certain it is operating correctly. A second later, we see the fleeting outline of a HUMAN SHAPE appear behind her. <b> STALKING POINT OF VIEW </b> Three feet from Rennie. She spins around to climb out of the hoist box and GASPS. <b> REVERSE ANGLE </b> She's facing MCCULLOCH. He immediately reaches past her, yanking the lever back to its center position, and: <b> THE ANCHOR CHAIN (SECOND UNIT) </b> grinds to a halt. <b> RETURN TO SHOT </b> as McCulloch faces her, angrily grabbing Rennie's arms, shouting over the storm. <b> MCCULLOCH </b> You had me worried to death! <b> RENNIE </b> But Sean said... <b> MCCULLOCH </b> I'm the one you should be listening to! Do you think dropping an anchor in the middle of a storm makes any sense whatsoever? She tries to find some defense, but McCulloch leads her off before any wards come forth. <b> CLOSE UP - EXERCISE MAT </b> as a pair of SKEET RIFLES, three FIRE AXES, a FLARE GUN and several POOL CUES are dumped onto the foam padded plastic. <b> INT. EXERCISE ROOM - NIGHT </b> where Julius has gathered his small group of vigilantes, including Miles and Wayne. <b> JULIUS </b> I managed to scrounge this shit from the game room and hallways. Grab what you want. Wayne takes one of the rifles; Miles grabs the axe. <b> WAYNE </b> What are you taking, Julius? <b> JULIUS </b> (flexes fists) Nothin'. <b> WAYNE </b> (dead serious) We're talking the possibility of Jason Voorhees here. Julius pauses. He's not stupid. <b> JULIUS </b> Nothin' but this gun. He reaches down, picking up the other rifle. And they move. <b> INT. STATEROOM HALLWAY/RENNIE'S ROOM - NIGHT </b> as McCulloch guides his niece down the hallway, swinging her door open. <b> RENNIE </b> Can't we at least talk about it? <b> MCCULLOCH </b> I refuse to discuss this ridiculous notion that a ghoul is terrorizing this ship. <b> RENNIE </b> But what about the drowning boy I've been seeing? He avoids eye contact. McCulloch takes her hand, ushering her across the threshold. She's standing inside her room now; he's in the hallway. <b> MCCULLOCH </b> Whatever you've been...imagining... has nothing to do with Jason Voorhees. (pause) I want you to be safe, Rennie. That's all I care about. <b> RENNIE </b> I'm not staying in my room, Uncle Charles. <b> MCCULLOCH </b> This isn't a request. He closes the door on her face, pulling out a key, locking the dead bolt. She pounds on it from the other side. <b> RENNIE (O.S.) </b> Uncle Charles! He ignores her, briskly walking away. <b> INT. RENNIE'S STATEROOM - SAME TIME </b> as she throws her fists against the door a final time, realizing it's futile. <b> INT. POWER ROOM - NIGHT </b> Steam continues to seep from the maze of criss-crossing pipes. Wayne appears on one of the catwalks. He's holding the skeet rifle under one arm, using the sun gun off his video camera to guide him. <b> WAYNE </b> J.J. -- you down here? <b> CLOSER ANGLE </b> as Wayne carefully lets his light guide him down the precarious walkway. An unexpected blast of steam scares the crap out of him, causing him to stumble. <b> INSERT - WAYNE'S GLASSES (SECOND UNIT) </b> --They slip off the bridge of his nose, skittering down through the catwalk and pipes to God knows where. <b> WAYNE </b> lies helplessly on the metal grid work, realizing his bleak predicament has just been squared. He pulls himself to a standing position again. <b> WAYNE </b> We got a major problem, Wayne. <b> WAYNE'S BLURRY POINT OF VIEW </b> His vision now gives him shadows and shapes rather than crisp images. He raises the gun and continues unsteadily forward. <b> POINT OF VIEW THROUGH GRID WORK </b> as Wayne inches forward. Camera slowly PANS INTO A PROFILE OF JASON, watching him from a catbird seat. <b> WAYNE </b> takes another step, almost tripping on a set of stairs leading down to the next level. And when he arrives there... <b> WAYNE'S BLURRY POINT OF VIEW </b> <b> ...A LARGE FIGURE STEPS OUT, HOLDING WHAT APPEARS TO BE A </b><b> KNIFE. </b> <b> WAYNE </b> instantly raises the rifle and FIRES... <b> WAYNE'S BLURRY POINT OF VIEW </b> ...and the body goes down. He's hit him! <b> WAYNE </b> stands there, breathing some relief. He gets an idea, looking through his camcorder eyepiece. Wayne begins to adjust the eyepiece diaptor. <b> WAYNE'S POINT OF VIEW (B & W/VIEWFINDER MATTE) </b> as the figure on the ground slips in and out of focus, finally becoming crisp. WAYNE HAS SHOT A CREW MEMBER -- the same good looking one Tamara and Eva ogled earlier. He's holding a screwdriver from his waist band tool set, not a knife. <b> WAYNE </b> slowly lowers his camera as his heart rises into his throat. <b> WAYNE </b> No... He raises his camcorder again, hoping a second view will reveal a dead Jason rather than this young man. <b> WAYNE'S POINT OF VIEW (B & W/VIEWFINDER MATTE) </b> He gets half his wish: a HOCKEY MASK NOW FILLS HIS FRAME...but Jason is far from dead. Wayne catches a split- second glimpse of Jason's fist coming towards him, then the camera is KNOCKED FROM HIS EYE AND THE WORLD BECOMES <b> DARK AND BLURRY. </b> <b> WAYNE </b> screams, blindly running as fast as he can. He trips, picking himself up, stumbling down the catwalk stairs. Wayne makes it about ten feet before he stumbles over something, bringing with it a harsh strum from an <b> ELECTRIC GUITAR. </b> <b> ANGLE - WAYNE'S FEET </b> Sure enough, his left shoe is resting on the pickups of a blood-streaked Gibson Flying V. <b> TIGHT ON WAYNE </b> --sprawled out on the metal floor. He gropes around, his hands feeling something. It sends chills from his groin up through his scalp. <b> WAYNE </b> No no no... <b> REVERSE ANGLE </b> Wayne's hands are touching J.J.'S BLOODY FACE, A LARGE CRACK IN HER SKULL. He doesn't have time to scream or cry because <b> JASON </b> hoists him off of J.J.'s body and flings him into: <b> THE SHIP CIRCUIT PANEL (EFX) </b> which shorts out with a fanfare of ELECTRICAL SPARKS <b> AND FIRE, INSTANTLY FRYING WAYNE. </b> <b> INT. BRIDGE - SAME TIME </b> as the overhead lights briefly flicker, then resume normal operation. Sean stands opposite the navigational chart, ping-ponging between it and the ship's computers as Miss Van Deusen paces nervously. <b> MISS VAN DEUSEN </b> What was that?? <b> SEAN </b> (very worried) I don't know. <b> MISS VAN DEUSEN </b> (trying not to panic) What happens if we don't get control of the ship, Sean? I want you to tell me the truth. <b> SEAN </b> (beat) We could hit a reef, collide with another ship...we could be out here for weeks before anybody spotted us. They are suddenly jolted with a DOOR SLAM as McCulloch storms onto the bridge. <b> MISS VAN DEUSEN </b> Did you find Rennie? <b> MCCULLOCH </b> She's locked safe in her room, no thanks to either of you. (like Sean isn't even in the room) Has he brought it back on course yet? Sean doesn't look at him, still trying to assimilate the wall of components. <b> MISS VAN DEUSEN </b> He's doing the best he can, Charles. <b> MCCULLOCH </b> He's the son of the Captain, for Chrissakes. You'd think he'd be able to operate this thing! Sean closes his eyes, trying to keep from losing his mind and temper. A fierce WAVE slaps the windows in front of Sean's face, motivating him to get his shit together. He checks the Omega and LORAN. <b> MCCULLOCH </b> Well? Sean doesn't answer, moving to the seat behind the helm. His father's seat. Sean takes the chair, adjusting the wheel, watching the compass. He studies a series of buttons on the console. <b> CLOSE UP - WALL OF BUTTONS </b> We PAN across them, stopping on one labeled "FIRE ALARM - DO NOT BREAK EXCEPT IN CASE OF EMERGENCY." Camera continues around to find we are in the POWER ROOM, NOT on the bridge. Our vision suddenly lands on JASON, staring at the alarm button, considering. He glances back over his shoulder. <b> JASON'S POINT OF VIEW (EFX) </b> Wayne's body is NOW ON FIRE...AND THE BLAZE IS SPREADING <b> THROUGH THE ROOM. </b> <b> INT. BRIDGE - SAME TIME </b> as Sean makes up his mind, flipping several toggle switches. <b> INSERT - AUTO PILOT COMPUTER </b> as Sean flips the last toggle and a green light illuminates, indicating the AUTO PILOT is in effect. <b> RETURN TO SHOT </b> <b> SEAN </b> It worked...we're back on course! Sean feels his confidence instantly rejuvenated. Miss Van Deuten immediately embraces him. But a fraction of time later: <b> TIGHT ON FIRE ALARM BUTTON </b> Jason's fist SMASHES the alarm button... <b> INT. BRIDGE - CONTINUOUS </b> ...and a LOUD SIREN cries out across the entire vessel. The blood drains from Sean's face. <b> MCCULLOCH </b> What's that? <b> SEAN </b> The fire alarm... <b> VARIOUS ANGLES ON BOARD SHIP - NIGHT </b> as the shrieking alarm assaults the main deck, hallways and corridors, giving Julius, Miles and Wayne deep pause for thought. <b> INT. RENNIE'S STATEROOM - SAME TIME </b> as the alarm bombards Rennie's ears like everybody else's. She hurries to her curtained porthole window, working up the energy to look outside. Rennie gets a grip on them, FLINGING THEM OPEN. The DECK HAND'S CRAZED FACE IS GAZING BACK AT HER. Rennie screams; a second later he hurries off. <b> INT. BRIDGE - NIGHT </b> as McCulloch tears open a cabinet door labeled EMERGENCY FLARE GUN. The siren continues to blast. <b> MCCULLOCH </b> Can you shut that damn thing off?? Sean moves to a bank of switches, his eyes darting around for the appropriate switch. Miss Van Deusen sees McCulloch remove the FLARE GUN from the cabinet. <b> MISS VAN DEUSEN </b> We already thought of that -- nobody could possibly see it in this storm... <b> MCCULIACH </b> There's only one person who needs to see it. And I'm going to find him. <b> MISS VAN DEUSEN </b> What about the fire?? <b> MCCULLOCH </b> I doubt very much that one even exists. <b> MISS VAN DEUSEN </b> What are you talking about? <b> MCCULLOCH </b> Use some common sense! Setting off a fire alarm causes panic...the same kind of panic caused by suggesting Jason Voorhees is on board. (resolved) Enough is enough. He marches out the door. Sean finds the alarm kill switch, flipping it. The excruciating siren vanishes. He grabs a pair of rain jackets, tossing one to Miss Van Deusen. <b> SEAN </b> We have to get everybody together just in case the fire's for real. Sean heads for the door, shoving it forward. <b> EXT. DECK - ON DOOR </b> as it slams open...and JULIUS steps out, not Sean, from a different deck door. TRACK with him as he treads along the side of the ship, skeet rifle raised. <b> JULIUS' POINT OF VIEW </b> walking past the lifeboat stations, the wind and precipitation battering the small boats. With no warning, <b> AN OBSCURE FIGURE LEAPS OUT, GRIPPING AN AXE. </b> <b> JULIUS </b> shoves the gun stock into his shoulder and takes instantaneous aim...but he doesn't shoot. He slowly lowers the rifle. <b> ANOTHER ANGLE </b> as MILES lowers the axe. They've just scared the shit out of each other. <b> MILES </b> I'll take the upper deck. Julius nods. They separate. Neither boy notices the smoke which is starting to emerge from a deck vent... <b> INT. POWER ROOM - NIGHT (EFX) </b> Filled with black smoke. The fire is spreading dangerously close to a series of hoses attached to a fuel pump, leading to tanks below. A sign over them reads: <b> DANGER - FUEL TANKS. </b> <b> EXT. DECK POOL - NIGHT </b> --steaming and far from calm as the weather blitzes it. Miles appears, climbing a ladder to the upper deck level. <b> POINT OF VIEW THROUGH LADDER </b> Someone is spying on Miles from below, watching his every step. <b> EXT. UPPER DECK - CONTINUOUS </b> as Miles arrives, axe raised. He pauses to regard his surroundings, then moves on. RACK FOCUS TO FIND JASON RIGHT BEHIND HIM, having followed Miles up the stairs. <b> ANOTHER ANGLE </b> Only darkness and rain for a beat, then Miles materializes, curving around the gargantuan smokestack. He passes us and we SWING AROUND, now looking at the back of his head. He takes three more steps and JASON STEPS INTO THE FOREGROUND. Miles senses his presence and JERKS <b> AROUND, RAISING THE AXE, BRINGING IT DOWN ON JASON'S </b><b> HEAD... </b> ...but Jason easily grabs the axe handle before it makes contact, flinging it away. <b> EXT. LOWER DECK - ON JULIUS </b> He's pacing along when a clattering noise from above makes him stop. Suddenly MILES' AXE THUDS INTO THE MAHOGANY DECK NEXT TO HIS FOOT. Julius gazes at it, jerking his head upward. <b> JULIUS </b> Miles?? His answer is a LOUD CRACK OF LIGHTNING. At the same time: <b> RUNNING WITH MILES </b> He's scrambling as fast as he can across the slippery deck as the monster relentlessly pursues him. <b> JASON'S POINT OF VIEW </b> He's having no problem catching up to the defenseless teenager. <b> EXT. DECK STAIRS - SAME TIME </b> as Julius zooms up them to aid his comrade. <b> EXT. RADAR MAST - NIGHT </b> as Miles slides up to the mast and begins scaling it. He glances downward and sees: <b> MILES' POINT OF VIEW </b> Jason is right at his heels. <b> MILES </b> slips on a rung, regains control, and continues upward. He makes it three more steps, almost at the uppermost point when JASON GRABS THE BACK OF HIS COAT, TEARING HIM <b> OFF THE MAST. </b> <b> STUNT FREEFALL </b> Miles cries out as he FREEFALLS BACKWARDS, somersaulting and twisting like he's doing one of his better dives... <b> CLOSE UP - MILES' FACE </b> ...Empty space for a half-second, then MILES' FACE JOLTS INTO FRAME with a look of ultimate agony. Something has abruptly stopped his fall. Something quite fatal. <b> EXT. DECK - ON JULIUS </b> coming around a corner, stopping dead in his tracks, his stomach wrenching as his eyes fall on: <b> MILES (EFX) </b> ...who is staring right back at him with dead pupils. <b> MILES HAS BEEN HORRIBLY IMPALED OM A SHIP FLAGPOLE. </b> <b> JULIUS </b> doesn't get the chance to grasp the reality of it because <b> JASON'S HAND GRIPS HIS SHOULDER, SPINS HIM AROUND AND </b> SLUGS HIM SQUARELY IN THE FACE. The force of it sends the boxer REELING BACKWARDS OFF THE RAILING... <b> EXT. STORMY OCEAN (TANK) </b> ...and Julius SPLASHES INTO THE ROUGH SEA. He's quickly swallowed by the torrential waters. <b> INT. RENNIE'S STATEROOM - NIGHT </b> as Rennie's HAND jiggles her doorknob again, confirming that it's locked tight. RISE to find her desperate face; she begins furiously pacing and we DOLLY BEHIND HER ...but Rennie stops cold upon hearing: <b> YOUNG JASON (O.S.) </b> Hhhhelp....me.... Rennie whirls into a CLOSE UP, staring with disbelief at: <b> YOUNG JASON (EFX) </b> ...who is standing on the oval rug in her stateroom, his hands reaching out to her. But then comes the inexplicable: THE OVAL RUG TURNS INTO LAKE WATER AND JASON SINKS INTO IT. He's drowning in the middle of her room, choking on murky water. <b> YOUNG JASON </b> Hhhhelp me....I'm drowning... <b> RENNIE </b> stands frozen, feeling herself drawn to him like a magnet. She crawls to the edge of her rug, which is now a deep lake, and extends her arms to him. <b> YOUNG JASON </b> grabs her hand, pulling hard, then grinning wide. <b> RENNIE </b> feels the skin on her face crawling off her skull, her eyes expanding because she's now looking at: <b> HERSELF! </b> Rennie is holding onto herself, about four years younger in a bathing suit, drowning in the lake. YOUNG RENNIE. <b> YOUNG RENNIE </b> Hhhhelp....me.... <b> RENNIE </b> screams with guttural fear, letting go of herself, watching her younger self drown in the hole in her room. <b> YOUNG RENNIE </b> disappears under the surface of the water...which seconds later CHANGES BACK INTO HER OVAL RUG. <b> NEW ANGLE </b> as Rennie moves away, tears rolling down her face, utterly confused. She backs against the wall next to her porthole window and THE REAL JASON'S FIST SMASHES THROUGH THE WINDOW, GRABBING HER THROAT. Rennie struggles, gasping for air as he attempts to strangle her. <b> CLOSE ON RENNIE'S HAND </b> groping for a weapon to stop him, her fingers skittering across her table like a spider. <b> TWO SHOT - RENNIE AND JASON </b> Her head is pulled taut against the wall just below the porthole, with Jason's hideous mask framed in the circular shattered window. She's slowly dying. <b> CLOSE ON RENNIE'S HAND </b> Her movements slow as the oxygen leaves her system. But Rennie's fingers miraculously find a recognizable object: the ink-dip pen given to her by Miss Van Deusen. She seizes it, getting a firm grip. <b> CLOSE ON JASON </b> as Rennie JABS THE PEN BACKWARDS, SENDING THE SHARP INSTRUMENT THROUGH THE EYEHOLE OF HIS MASK. Jason instantly releases her, reeling backwards. <b> RENNIE </b> sinks to the floor, scrambling on all fours to get as far away from the porthole as possible. She makes it across the room to her stateroom door just as: <b> THE DOOR </b> is SLAMMED OPEN FROM THE OTHER SIDE. She shrieks in terror but it's SEAN who is standing there. <b> SEAN </b> Rennie...?? <b> RENNIE </b> (pointing) The window... Sean rushes to the shattered porthole, looking out, seeing nothing. He steps back to her. <b> RENNIE </b> I don't understand what is happening to me... She breaks down; he holds her. <b> SEAN </b> It's gonna be okay... <b> INT. POWER ROOM - NIGHT (EFX) </b> ...but Sean couldn't be more wrong. The flames are lapping at the fuel pump and hoses, furiously burning down into the tank. A second later the whole thing <b> EXPLODES IN A BALL OF FIRE. </b> <b> EXT. SHIP HULL - UNDERWATER (EFX/MODEL?) </b> as a huge HOLE is blown through the thick steel hull: <b> INT. RENNIE'S STATEROOM - SAME TIME </b> The ship noticeably rocks from the explosion. Rennie clings to him fearfully. <b> RENNIE </b> What is it?? One second later, the lights begin to flicker. <b> SEAN </b> The power room... <b> INT. POWER ROOM - SAME TIME (EFX) </b> as huge amounts of water rush in from a gaping hole in the hull. <b> INT. SHIP KITCHEN - SAME TIME </b> as the overhead lights flicker over McCulloch. There's some fear mixed with the anger as he grips his flare gun, moving onward. <b> PONT OF VIEW FROM KITCHEN OVENS </b> Someone is crouched behind a massive convection oven, spying on McCulloch. <b> MCCULLOCH </b> almost flinches when the lights die and he's plunged into blackness. He moves forward, every step tentative. He passes the convection ovens and we REMAIN on them, spotting the frightened face of the DECK HAND in the shadows. The deranged old man is very sober now, clutching a LARGE KITCHEN KNIFE for defense. <b> INT. RENNIE'S STATEROOM - SAME TIME </b> Sean paces feverishly in the blackness of her room, trying to think, talking to himself. <b> SEAN </b> Rule one, don't panic. Rule two, assess the damage and act accordingly... <b> RENNIE </b> Is the ship going to sink?? He returns to Rennie, the panic settling back in. <b> SEAN </b> I don't know. Her ultimate fear is staring her straight in the face. Suddenly the dim blue lights flicker on. <b> SEAN </b> The emergency lights just kicked in... Sean makes Rennie look into his eyes. His words are meant to convince himself as much as Rennie. <b> SEAN </b> We'll be okay. I want you to wait by the lifeboats, just in case. <b> RENNIE </b> (terrified) I'm not going near any lifeboat! <b> SEAN </b> But Rennie... <b> RENNIE </b> I'm not!! <b> INT. SHIP RESTAURANT ROOM - SAME TIME </b> as Miss Van Deusen gathers a handful of students who are panicking, sitting them down. <b> MISS VAN DEUSEN </b> Everybody wait right here until I come back with the others -- understand? They nod, frightened to death. She dashes away, carrying us into a view of the dining room windows. No one notices the SILHOUETTE OF JASON passing by on the outside desk. <b> INT. ENGINE ROOM - SAME TIME (EFX) </b> Sea water is pouring into the ship's motors. Clouds of steam and black smoke fill the room as the engine bearings begin to GRIND. <b> INT. SHIP HALLWAY - SAME TIME </b> as McCulloch rushes up to Rennie's already open door, cautiously entering with flare gun raised. <b> MCCULLOCH </b> Rennie?? <b> MCCULLOCH'S POINT OF VIEW </b> The room is empty, shards of the porthole glass scattered across her rug. He steps over to it, bringing his head up to the gaping hole, peering outside. We wait for his attack...but it doesn't come. McCulloch's eyes take us to something across the room. The bathroom door is afar. <b> MCCULLOCH </b> cautiously steps up to the door, silently grabbing the knob and SWINGING IT OPEN. It's empty. He hears something, spinning around. Again, nothing is there. McCulloch quickly moves to the telephone and dials. A few seconds pass. <b> MCCULLOCH </b> Come on, answer!! <b> INT. BRIDGE - SAME TIME </b> TIGHT on the bridge telephone, ringing repeatedly. RISE TO FIND JASON, ignoring the phone, scrutinizing the deck below through rain-streaked windows. <b> JASON'S POINT OF VIEW </b> Miss Van Deusen is darting across the deck, gathering up a trio of terrified seniors. <b> RETURN TO SHOT </b> Jason methodically moves to the bank of switches, studying them. <b> INSERT - CONSOLE </b> In large, unmistakable letters over a red button are the words "ABANDON SHIP ALARM." He flips back the plastic safety cover, exposing the button. <b> INT. BOWELS OF SHIP - SAME TIME </b> A horrible grinding sound echoes through the narrow corridor. Sean and Rennie appear at the opposite end, coughing on the black smoke which clouds their passageway. Sean looks down, seeing that they are standing in a puddle of water. <b> SEAN </b> Water has gotten to the engines. (coughs) We have to get everybody off this ship... <b> INSERT - ABANDON SHIP BUTTON </b> as Jason presses it with firm deliberation, and: <b> INT. BOWELS OF SHIP - CONTINUOUS </b> A WHOOPING SIREN blasts through the passageway. Sean and Rennie have no time to react because: <b> ANGLE - CORRIDOR (EFX) </b> A sealed compartment door EXPLODES OPEN WITH THE PRESSURE <b> OF SEA WATER... </b> <b> REVERSE ANGLE (EFX) </b> ...and a WALL OF WATER ENGULFS.RENNIE AND SEAN, KNOCKING THEM DOWN. Sean fights to pull her up, but not in time for her to witness: <b> WAYNE'S CHARRED CORPSE (EFX) </b> which bobs up in front of her. Rennie cries out, scrambling to grab onto Sean as what's left of Wayne's body washes past them. <b> EXT. DECK - NIGHT </b> as a door opens and Miss Van Deusen guides a half-dozen SENIORS over to the LIFEBOAT STATIONS. <b> MISS VAN DEUSEN </b> (shouting over storm) Everybody climb in! They follow her orders as the Abandon Ship alarm wretches on. But little do they know that: <b> STALKING POINT OF VIEW </b> Someone is briskly moving towards the group and Miss Van Deusen. Just as we are within a few feet of her... <b> REVERSE ANGLE </b> --It's MCCULLOCH who's approached them. He grabs Miss Van Deusen, shaking her violently. <b> MCCULLOCH </b> What did you do with Rennie?? <b> MISS VAN DEUSEN </b> Nothing! I went to her cabin and... McCulloch rushes off before she can finish. Miss Van Deusen turns back to the other kids, helping them into the boat. <b> MISS VAN DEUSEN </b> Everybody hurry...please... <b> EXT. DECK - CLOSE ON MAHOGANY DECKING - SAME TIME </b> We slowly DOLLY BACKWARDS until Miles' AXE comes into frame, still stuck in the mahogany decking. A beat, then <b> JASON'S HALAL DISLODGES IT FROM THE WOOD. </b> <b> INT. CORRIDOR - NIGHT </b> as Sean climbs up from below, soaked to the bone, pulling up a half-conscious Rennie. Sean carries her around a corner, where he collides with McCulloch. McCulloch pulls Rennie away from him. <b> MCCULLOCH </b> She never should've set foot on this ship. This is your fault! <b> SEAN </b> This is Jason's fault! <b> MCCULLOCH </b> (shouting) Not another word, do you hear me?? <b> EXT. LIFEBOAT STATIONS - NIGHT </b> as Miss Van Deusen throws the "down" lever and the lifeboat hoist begins to lower the boat. Camera SLOWLY <b> CREEPS IN A SEMI-CIRCLE AS A SILHOUETTED FIGURE STEPS </b><b> INTO A POOL OF LIGHT BEHIND HER. JASON. </b> <b> ANGLE - LIFEBOAT </b> One of the students screams, the others clinging together upon the sight of this infamous monster. But the boat is already over the edge, past the point of return. And lowering at a snail's pace. <b> MISS VAN DEUSEN </b> turns to see JASON APPROACHING THEM WITH AXE RAISED. She backs away but Jason ignores her, heading directly for the hoist. He arches back with his weapon and SLICES <b> DOWNWARD. </b> <b> INSERT - HOIST CABLE (SECOND UNIT) </b> as Jason's axe CHOPS THE CABLE IN TWO, and: <b> EXT. SHIP/OCEAN (TANK) </b> The bow cable SNAPS, DUMPING THE HALF DOZEN TEENAGERS INTO THE TURBULENT SALT WATER. They last about five seconds before succumbing to a drowning death. <b> MISS VAN DEUSEN </b> sees it all, her intestines constricting in agonizing knots. She summons all her rationale and sends it down to her legs, running away as fast as she can. <b> MISS VAN DEUSEN'S POINT OF VIEW </b> --knocking down deck tables, chairs and chaise lounges as she flees. The creative writing teacher swerves around a column, heading for an interior door, sliding to a stop as it BANGS OPEN IN FRONT OF HER. McCulloch steps outside, carrying Rennie, with Sean right behind her. Rennie is conscious now, squirming free of her uncle upon the sight of Miss Van Deusen. <b> ANGLE TO INCLUDE ALL </b> as Rennie rushes into Miss Van Deusen's arms. The teacher holds her, beginning to cry herself. <b> MCCULLOCH </b> Why aren't you with the others, woman?? Finally the message comes forth: <b> MISS VAN DEUSEN </b> Jason...he has an axe... His face grows taut with anger. <b> MCCULLOCH </b> Jason Voorhees is dead!! A PRIMAL SCREAM OF AGONY immediately cries out behind them, the words unintelligible. They turn around to witness THE DECK HANG STAGGERING TOWARDS THEM, GRIPPING <b> THE KITCHEN KNIFE. </b> <b> MCCULLOCH </b> raises the flare gun with zero hesitation and FIRES IT... <b> ANGLE - DECK HAND (EFX) </b> ...and the charge EXPLODES INTO HIS CHEST. He stands there with his chest smoldering, almost like a gargoyle in effigy. A second later the poor old man falls forward, and: <b> CLOSE ON HIS BACK (EFX) </b> They all see that JASON'S AXE HAS BEEN BURIED IN HIS <b> BACK. </b> <b> RETURN TO MASTER </b> McCulloch gazes with utter disbelief. <b> MCCULLOCH </b> Dear Christ... <b> SEAN </b> We have to get off this ship!! They back away from the horrid sight and begin to run, the Abandon Ship alarm still attacking their ears. <b> EXT. LIFEBOAT STATIONS - NIGHT </b> as McCulloch, Miss Van Deusen, Rennie and Sean scramble to the closest lifeboat. <b> SEAN </b> Everybody in -- I'll get the hoists McCulloch has no time for politeness, moving to the lifeboat ahead of the women. Rennie stops cold, gazing classy-eyed at the small boat. <b> MISS VAN DEUSEN </b> Come on, sweetheart -- get in... But she doesn't budge. McCulloch levels wild eyes on her, quickly climbing back down. <b> MCCULLOCH </b> Get in the boat, Rennie! <b> RENNIE </b> I...I can't... <b> MCCULLOCH </b> (shaking her) You can and you will!! He tries to slap her out of it, dragging her over to the boat, ignoring her terror-stricken frenzy. <b> SEAN </b> Stop it!! <b> MISS VAN DEUSEN </b> Leave her alone, Charles! Miss Van Deusen quickly moves to a hysterical Rennie and holds her, eyeing McCulloch vehemently. <b> EXT. DECK - TIGHT ON DEAD DECK HAND - SAME TIME </b> as rain begins to wash the blood from his back. JASON'S FOOT TRUDGES INTO FRAME...then his HAND REACHES DOWN, <b> RETRIEVING HIS AXE FROM THE DECK HAND'S SPINE. </b> <b> EXT. LIFEBOAT STATIONS - SAME TIME </b> as Rennie clings to Miss Van Deusen, crying. <b> MISS VAN DEUSEN </b> It's the only way, Rennie. Let's get in the boat now, okay? Please...for me? Rennie finds herself nodding. Miss Van Deusen helps the trembling girl up the steps, an angered McCulloch right behind. <b> INT. LIFEBOAT - CONTINUOUS </b> as Rennie climbs over the boat edge, RECOILING AT THE SOUND OF A SNARLING DOG. Toby is curled up in the corner of the lifeboat, teeth bared. <b> RENNIE </b> Toby... She climbs in, moving to her equally, relieved dog, McCulloch and Miss Van Deusen right behind her. <b> INSERT - HOIST BUTTON (SECOND UNIT) </b> as Sean jabs it and the hoist motor kicks in. <b> EXT. SHIP - WIDE SHOT (EFX) </b> just as a huge BOLT OF LIGHTNING cracks over the smoke stack and upper deck. JASON steps out from behind it, gaping down on them with frightening omnipresence. Gripping the bloody axe. <b> EXT. LIFEBOAT STATIONS - CONTINUOUS </b> Sean climbs in the boat as it continues to lower. He takes one look back at the ship and sees: <b> JASON </b> rapidly moving down the staircase towards them. Sean's view is CUT OFF as the lifeboat sinks below deck level. <b> RETURN TO SHOT </b> as Sean's eyes dart around, down to the sea, up at the hoist. <b> SEAN </b> Come on...faster.... <b> JASON'S POINT OF VIEW </b> trampling towards the hoist, about thirty feet away now. The boat has already disappeared over the edge. <b> EXT. SHIP/STORMY SEA - NIGHT (TANK) </b> as the lifeboat continues to lower, about ten feet from making contact with the tumultuous ocean. The ship's hull is crooked and sinking. <b> TRACKING WITH JASON </b> as he relentlessly moves to the hoist cable, raising his axe. <b> EXT. SHIP/STORMY SEA (TANK) </b> as the ship finally touches water, and: <b> INSERT - HOIST CABLE (SECOND UNIT </b> Jason's axe blade CHOPS THE CABLE... <b> EXT. SHIP/STORMY SEA (TANK) </b> ...and the hoist cable falls limply over them. Jason's too late. Sean looks up and sees: <b> JASON </b> standing by the hoist, hovering over the edge. Very angry. <b> SEAN (TANK) </b> grabs an oar, turning back to McCulloch. <b> SEAN </b> Start rowing!! McCulloch takes the oar as Miss Van Deusen holds onto Rennie tightly, the girl's eyes squeezed shut. Sean looks up at the ship again, and: <b> SEAN'S POINT OF VIEW </b> Jason is none. <b> EXT. SHIP/STORMY SEA (TANK) </b> Sean looks around with confusion as huge waves, wind and rain pummel them. <b> SEAN </b> He's gone... <b> POINT OF VIEW FROM WATER (TANK) </b> ...or is he? We're moving towards the lifeboat at water level, almost like a shark preparing for attack. <b> INT. LIFEBOAT (TANK) </b> Sean breathes with some relief, resuming his rowing with McCulloch. They get about three strokes apiece before: <b> A DARK FIGURE (TANK) </b> lunges from under the ocean surface, grabbing onto Sean. Everybody SCREAMS...but it's JULIUS, gasping for oxygen, spitting up seawater. Sean pulls him over the edge. <b> SEAN </b> It's Julius! Miss Van Deusen moves to help him and we: <b> SLOW DISSOLVE TO: </b> <b> EXT. STORMY OCEAN - WIDE SHOT - DAY (SECOND UNIT) </b> The ship is gone now, the lifeboat a speck in the ocean. <b> INT. LIFEBOAT - DAY (OCEAN?) </b> The water is less rough now, the rain replaced with fog. Julius has taken McCulloch's place behind an oar; McCulloch is flanking his shivering niece with Miss Van Deusen. <b> MCCULLOCH </b> (miserable) If we don't find the shore soon we're all going to die. Sean tries to ignore him, keeping his mind on rowing. <b> MISS VAN DEUSEN </b> (unable to hide fear) Do you know where we are, Sean? Sean pauses, utterly exhausted. He thinks for a moment, remembering his father's gift. Sean reaches into his coat pocket, removing the pocket navigational calculator. He stares at it long and hard. Julius looks over at him, seeing that Sean is on the verge of tears. He grips his shoulder. <b> JULIUS </b> Hey man, if I can make it, so can. you. Sean slowly nods, turning on the calculator. <b> SLOW DISSOLVE TO: </b> <b> EXT. OCEAN - NIGHT (TANK) </b> as the lifeboat rows into frame, the water relatively calm. <b> INT. LIFEBOAT - NIGHT (TANK) </b> McCulloch, Rennie and Miss Van Deusen are asleep, Sean and Julius rowing on sheer will power. Sean takes one more stroke, feels himself passing out, then regains his coherence again. Julius glances off the side of the ship for no particular reason, then does a doubletake. <b> JULIUS' POINT OF VIEW (SECOND UNIT - N.Y.) </b> They are rowing right past THE STATUE OF LIBERTY, illuminated in all its glory. <b> INT. LIFEBOAT (TANK) </b> Julius feels his eyes widening and a huge smile taking control of his haggard face. He tugs on Sean's sleeve, his eyes never leaving the monument. <b> JULIUS </b> Hey man, wake up! Check it out!! The other stir as well, opening their eyes, not sure if it's some kind of vision or if they are genuinely here. <b> JULIUS </b> God damn, we're in New York! You did it, my man!! Julius howls with delight, Miss Van Deusen hugging Rennie as Julius gives Sean the high-five. Toby barks. <b> WIDE SHOT - NEW YORK HARBOR - NIGHT (SECOND UNIT - N.Y.) </b> as the lifeboat rows toward the very famous skyline of Manhattan, twinkling in the near distance. We can hear the faint sound of Julius singing "New York, New York," relieved to be alive. They're going to make it. <b> EXT. EMPTY OCEAN - ANOTHER ANGLE (TANK) </b> as the sound of Julius' voice grows fainter. The water begins to ripple...then the top half of a HOCKEY MASK <b> BREAKS THE SURFACE FOR A BREATH OF AIR, SINKING AGAIN. </b> And swimming onward. <b> EXT. CANNERY HARBOR - NIGHT </b> as Julius and Sean row the lifeboat up to a narrow barge beneath deserted dock warehouses. They are not in the safest part of town by a longshot. <b> CLOSER ANGLE </b> as they climb onto the barge. Rennie breathes with relief as she steps off the boat. She takes a final glance back at it and sees: <b> YOUNG RENNIE </b> flailing her arms in the water right next to the lifeboat, drowning. <b> YOUNG RENNIE </b> Hhhhelp...me.... Suddenly a DECOMPOSED HAND REACHES UP FROM BELOW, <b> GRABBING HER, DRAGGING HER UNDER. </b> <b> EXT. BARGE - ON RENNIE </b> She gazes in utter shock, screaming: <b> RENNIE </b> No!!! They all follow her eyeline...but the water is calm, nothing there. <b> MISS VAN DEUSEN </b> (holding her) It's okay...you're safe now... McCulloch grits his teeth. <b> MCCULLOCH </b> Come on -- everybody up the ladder. He's the first one up. Sean looks at Rennie, concerned, then hoists Toby up in his arms. They all begin climbing the ladder. <b> CLOSE ON LADDER - NIGHT </b> as the last pair of feet disappear over the top edge of the dock. Camera PANS back down the rungs, finding the lifeboat and barge again. Suddenly JASON SPRINGS FROM THE WATER, CLIMBING ONTO THE BARGE. He gazes up at his new surroundings, quite different from all the years he's spent at Crystal Lake. But an item at the far end of the dock causes him the longest pause... <b> JASON'S POINT OF VIEW </b> A tattered billboard over one of the warehouses advertises the NEW YORK RANGERS HOCKEY TEAM, featuring a full shot of the HOCKEY-MASKED GOALIE. <b> JASON </b> looks at it long and hard. He tears off his life preserver wits renewed ambition. <b> WIDE SHOT - BARGE AND DOCK WAREHOUSES - NIGHT </b> as Jason heads up the ladder. He's about to take Manhattan. <b> EXT. CANNERY WAREHOUSE DISTRICT - NIGHT </b> as our survivors head into an isolated, foreboding group of dock warehouses and alleys. <b> MISS VAN DEUSEN </b> There must be a phone around here somewhere. <b> MCCULLOCH </b> A wonderful choice of places to dock a boat, Mr. Robertson. Sean looks away, trying to keep from losing his temper. <b> PREDATOR'S POINT OF VIEW - SAME TIME </b> We're spying on them from behind a stack of crates as they come in our direction. Waiting for the right moment. <b> RETURN TO SHOT </b> as they move towards the stack of crates. Without warning, a PAIR OF GANG BANGERS JUMP OUT, BOTH HOLDING GUNS. Nervous young druggies. <b> GANG RANGER #1 </b> Hands up!! <b> GANG BANGER #2 </b> Do it!! All hands go up. Gang Banger #2 grabs McCulloch's watch and wallet, skimming through a wad of bills and credit cards while #1 keeps them covered. <b> GANG BANGER #2 </b> Got some good shit here, holmes. <b> GANG BANGER #1 </b> (eyeing Rennie) You got that right... He steps over to Rennie, brushing her hair back with the barrel of his revolver, spotting the Statue of Liberty pendant Sean gave her. <b> GANG BANGER #L </b> Now ain't that sweet. He tears it off her neck, pocketing it. Sean angrily moves toward him and Gang Banger #l shoves the barrel against Rennie's temple. <b> GANG BANGER #1 </b> Go ahead, superman. Be a hero. Sean has no choice but to freeze. Julius flexes his fists, but he too has Gang Banger #2's gun leveled on him. McCulloch stares at the thugs with obvious contempt. It doesn't go unnoticed. <b> GANG BANGER #L </b> You got a problem, Dad? McCulloch offers some rare silence, shaking a "no" to the gun-toting kid. Rennie's dog-begins to growl, backing away, ready to defend her. Gang Banger #1 points his barrel at Toby with zero conscience, cocking back the hammer. <b> RENNIE </b> No! She pushes his arm to the side just as the bullet <b> FIRES... </b> <b> ANGLE - TOBY </b> as the bullet tears up asphalt next to the dog's paws. Toby sprints off into the darkness. <b> RETURN TO SHOT </b> Gang Banger #1 grabs Rennie by the hair, brutally jerking her head back. <b> MISS VAN DEUSEN </b> Please, don't hurt her... <b> GANG BANGER #L </b> Hurt this princess? (beat) Would I do that? They cough out laughs. Gang Banger #1 looks into Rennie's eyes, his barrel still on her skin. <b> GANG BANGER #1 </b> You look like a party girl, princess. How'd you like to go on a date with me and my friend? If you're free, that is. More phlegm-filled laughs. He drags her away, Gang Banger #2 backing away with him with his gun still trained on the others. <b> GANG BANGER #2 </b> You follow and we'll blow her fuckin' head off, comprende? The others watch helplessly as Rennie is abducted. <b> JULIUS </b> We can't let those gang-bangers get away, man... Julius starts to move after them. McCulloch grabs him. <b> MCCULLOCH </b> You heard him! We have to call the police Julius jerks away from McCulloch's grasp. But he knows McCulloch is right. <b> MCCULLOCH </b> Everyone split up -- we'll cover more ground that way. <b> MISS VAN DEUSEN </b> I don't think that's such a safe idea <b> MCCULLOCH </b> My niece's life hangs in the balance right now!! Every second counts. No more rebuttal. They hurry off. <b> EXT. GANG BANGER'S LAIR - NIGHT </b> It's a narrow passageway between warehouses...decrepit brownstones with shattered chicken-wire windows, moss growing on the bricks. The Gang Bangers appear with Rennie, dragging her down some concrete steps. <b> GANG BANGER #L </b> Welcome to the casbah, princess. PAN AROUND with them as they walk through a thick blanket of STEAM which pours out of a factory vent. We MOVE through the mist with them, revealing a tattered, rain- soaked couch and chair, upholstery shredded. A spool once used for telephone wire functions as their coffee table. They splash through puddles, throwing her down on the couch. <b> ANOTHER ANGLE </b> --looking back at the steam vent. JASON APPEARS IN THE <b> BILLOWING MIST. </b> <b> CLOSE UP - SYRINGE </b> as a yellowish liquid squirts out the dirty needle. WIDEN to find Gang Banger #2 holding it with transfixed eyes, his compadre holding a squirming Rennie down on the couch, tearing back her jacket to reveal a bare arm. <b> RENNIE </b> Please don't... <b> GANG BANGER #1 </b> Loosen up, baby. It'll feel way better if you're stoned. <b> CLOSE ON JASON'S FEET - SAME TIME </b> Amongst the slime and cigarette butts is a discarded syringe. Jason picks it up. <b> CLOSER ANGLE - COUCH </b> just as Gang Banger #2 jabs Rennie with the needle. Gang Banger #1 wrestles off his torn leather jacket, pushing Rennie back on the exposed foam padding as his friend watches excitedly. <b> GANG BANGER #1 </b> Slang us some more 'caine, JoJo. We're in for a long night. Gang Banger #2 runs out the back way. #1 tears open Rennie's blouse, his filthy mouth moving to her neck. Rennie spits in his face. He hesitates not in SLAPPING <b> HER HARD. </b> <b> GANG BANGER #1 </b> It's your parade, princess. Can be smooth or can be rough. Your choice. She closes .her eyes, trying to blot out what's about to happen. <b> GANG BANGER #1 </b> I think I'm in love. PUSH IN on his face as his neck arches down, bringing his lips toward her chest. Just before contact he GRUNTS <b> THICKLY, HIS EYES BUGGING OUT. </b> <b> WIDER ANGLE </b> Jason is standing right behind him, shoving something into his back, out of frame. He thrusts it again, bringing with it one more horrific grunt from the kid. Jason goes for number three and: <b> CLOSE UP - GANG BANGER #1'S CHEST (EFX) </b> Jason's syringe gets shoved completely through him, the needle sticking out his front side. <b> RENNIE </b> opens her eyes, looking into the dead boy's face as blood drips from his mouth. He collapses in front of her, giving way to a view of JASON TOWERING OVER HER. At the same time: <b> GANG BANGER #2 </b> comes around the corner. <b> GANG BANGER #2 </b> Forgot my money, holmes... Ha stops dead in his tracks at the sight of Jason. <b> GANG BANGER #2 </b> Who the fuck are you? Jason paces toward him. The kid glances at his dead friend arched over the couch, quickly whipping out his <b> .38. </b> <b> GANG BANGER #2 </b> You're dead, fuckhead. <b> BANG! </b> ...but Jason keeps on coming. Five shots later and Jason's still standing, easily picking up the slime ball and SHOVING HIM HEAD FIRST INTO THE MOSSY BRICK WALL. The kid falls in a bloody heap. <b> RENNIE </b> shoves Gang Banger #1 off of her as Jason returns his attention to her. She grabs a loose brick and FLINGS IT AT HIM, CRACKING HIS HOCKEY MASK, momentarily disorienting him. Rennie sprints away. <b> EXT. ALLEY #1 - NIGHT (LONG LENS) </b> as Julius runs into view, looking down a menacing alley, spotting a phone booth. He hurries for it. <b> PREDATOR'S POINT OF VIEW </b> Like a cat watching a bird, we watch Julius head for the booth. <b> JULIUS </b> slams open the booth door, grabbing the receiver, punching the "operator" digit. SLOWLY PUSH IN on him as he waits for an answer. Several more rings. <b> JULIUS </b> C'mon... Finally a click and muffled words from the operator. <b> JULIUS </b> Get me the police -- this is an emergency... <b> </b> SMASH! as JASON'S FIST CRASHES THROUGH THE BOOTH WINDOW, GRABBING JULIUS BY THE THROAT. Julius grips Jason's scaly arm with all his strength, staring at the cracked hockey mask framed in the shattered window. Julius summons all his strength, tearing free of Jason's grasp and running out the door. The phone is left dangling. <b> RUNNING WITH JULIUS (HAND HELD) </b> with no apparent direction. Literally running for his life. <b> TRACKING WITH JASON </b> He's just as quick, but smoother and more methodical. <b> JULIUS' POINT OF VIEW (HAND HELD) </b> heading up the alley, spotting a fire escape, diverting his course straight for it. <b> ANGLE - FIRE ESCAPE </b> as Julius LEAPS ONTO IT, dragging himself up, climbing as fast as is humanly possible. <b> ANGLE - JASON </b> ...but Jason is-far from human, easily negotiating the wrought-iron stairs and rapidly catching up. <b> EXT. ROOFTOP - CONTINUOUS </b> as Julius' head appears, clawing his way onto the tar- papered surface, running to the opposite side. A second later, JASON HOPS UP RIGHT BEHIND HIM. <b> REVERSE ANGLE </b> as Julius soon learns the awful truth that the only way up is the only way down...with the exception of a head- splitting freefall. No way is he gonna jump. Julius turns back to Jason, raising his fists, psyching himself up for the fight of his life. He whispers to himself: <b> JULIUS </b> Use the combos and keep the feet light... THE FIGHT BEGINS, man against monster, each sizing the other up. Jason takes the first swing, Julius deftly dodging him and countering with left-right-left combination. They have absolutely no effect. Julius follows up with a round of kidney punches. Again, nothing. Julius finds himself being forced back against the rings, which in this case is the edge of the roof. He risks a glance backwards and sees: <b> JULIUS' POINT OF VIEW </b> It's a long, rough way down. It's do or die time. <b> RETURN TO SCENE </b> as Julius SLAMS PUNCH AFTER PUNCH INTO JASON, forcing him back to the center of the rooftop, spending every last ounce of his energy in doing so. He throws one more feeble punch, knowing it's his last. <b> JULIUS </b> Take your best shot, motherfucker... Jason gladly obliges, winding up and recoiling with a punch none of us expected... <b> JULIUS' HEAD (EFX) </b> gets literally knocked off his shoulders, cascading off the edge of the rooftop, and: <b> ANGLE - SLANTED LOWER ROOF </b> --the decapitated head lands on a sloped roof below, rolling down towards street level and falling into a garbage-filled dumpster. <b> EXT. ALLEY #2 - NIGHT </b> as Rennie dizzily runs down the alley, the effects of the drugs kicking in. <b> RENNIE'S POINT OF VIEW (POST EFX) </b> Blurry, disoriented, erratic. Suddenly A FIGURE JUMPS OUT <b> FROM A CORRIDOR IN FRONT OF HER. </b> <b> RETURN TO SHOT </b> It's SEAN. He rushes to her, sensing her disorientation. <b> SEAN </b> Rennie...what'd they do to you?? <b> RENNIE </b> Drugs... (serious pause) Then Jason came. He's here, Sean. Oh Jesus. He never expected this. <b> SEAN </b> We have to find the others. Together they run off. <b> EXT. ALLEY #3 - NIGHT (OVERHEAD ANGLE) </b> as Miss Van Deusen briskly walks below us, far from relaxed in this threatening environment. <b> TRACKING SHOT </b> She moves forward, the only sound being her shoes against wet asphalt. Four more steps, then a DARK, OUT OF FOCUS <b> FIGURE STEPS OUT BEHIND HER WITH A GUN. </b> <b> VOICE </b> Freeze. RACK FOCUS to find a uniformed IRISH COP standing there, service revolver raised. McCulloch steps out from the alcove as well, recognizing Miss Van Deusen. <b> MCCULLOCH </b> It's okay -- she's with me. She turns around, lowering her hands, utterly relieved. <b> IRISH COP </b> My apologies, Miss. My unit's right over here. They head through an ABANDONED PARKING LOT towards a concrete wall with stairs; about six feet above the wall is an upper street, where his patrol car is parked. They get halfway through the lot when they hear: <b> SEAN (O.S.) </b> Hey! <b> REVERSE ANGLE </b> as Sean and Rennie run to join them from the alley. McCulloch rushes to his niece. <b> MCCULLOCH </b> Rennie, thank God... But Rennie goes to Miss Van Deusen instead. It's a bitter pill for McCulloch. <b> SEAN </b> Jason's here in New York. <b> MCCULLOCH </b> Don't be ridiculous! <b> MISS VAN DEUSEN </b> Is it true, Rennie?? She nods, unable to repress her fear. <b> IRISH COP </b> Is this the lass in question? <b> MCCULLOCH </b> (stewing) Yes. <b> IRISH COP </b> Who is...Jason? <b> MCCULLOCH </b> He's a walking corpse, a phantasm from hell. The others stare at McCulloch angrily. Miss Van Deusen turns to the confused policeman. <b> MISS VAN DEUSEN </b> I'm afraid you'll have some trouble believing us. <b> IRISH COP </b> So try me. <b> EXT. SQUAD CAR - NIGHT </b> parked above the abandoned garage, the interior dark. The Cop and our heroes appear in the background, coming towards it. <b> IRISH COP </b> You're right -- I find it a tall tale indeed. But you seem like honest folks so I'm inclined to believe at least some of it. <b> MISS VAN DEUSEN </b> (relieved) Thank you. The first thing we' have to do is find Julius. <b> IRISH COP </b> I'm sure he'll pop up soon enough. Why don't you climb in the back while I radio for backup. <b> ADJUST INTO A FULL SHOT OF THE BACK DOOR AS HE SWINGS IT </b> OPEN...but even in this darkness, we see that it's empty. They climb in. The Cop opens his drivers door, and... <b> INSERT - DOME LIGHT (SECOND UNIT) </b> The car dome light blinks on, and... <b> ANGLE - BACK SEAT </b> Our four survivors' faces are brightly illuminated, INSTANTLY CHANGING TO GASPS AND SCREAMS because: <b> THEIR POINT OF VIEW (EFX) </b> Julius' severed head is resting on the dash board, staring back at them!!! <b> ANGLE - COP </b> reacting to their terror, seeing Julius' head, quickly grabbing the radio mike. But he has no time for a message because JASON REACHES UP FROM THE PARKING LOT PIT BELOW, GRABBING THE COP'S ANKLE, DRAGGING HIM DOWN. The radio is still in his grasp. <b> INSERT - DISPATCH RADIO (SECOND UNIT) </b> as the radio cord grows taut, finally snapping. The Irish cop's awful yell echoes over it, silencing after a sick THUD. <b> INT. SQUAD CAR - CONTINUOUS </b> The foursome instantly try to flee the car, but police cars have no door handles in the back. <b> SEAN </b> There aren't any handles!! Cocaine flowing through her veins, Rennie acts hyperkinetically, scratching her way over the seats just as: <b> JASON </b> appears at the parking lot stairs, STALKING STRAIGHT <b> TOWARDS THE CAR. </b> <b> INT. SQUAD CAR - CONTINUOUS </b> There is no time for escape. Rennie finds the ignition and fires it up, jamming it into drive and STOMPING ON THE ACCELERATOR. Julius' head rolls off the dash, onto the floorboards. <b> RENNIE'S POINT OF VIEW (POST EFX) </b> Her vision is still a stoned one but clear enough to set her target. We come straight at the abominable creature and: <b> WHAM! (EFX) </b> Jason is mowed down. <b> RENNIE </b> slams on the brakes, jerks it into reverse and FLOORS IT <b> AGAIN. </b> <b> CLOSE ON JASON (EFX) </b> as the automobile grinds back over him a second time. <b> RENNIE </b> stomps on the brake pedal and the tires SCREECH TO A HALT. They all take a moment to catch their breath, looking out the front window... <b> THEIR POINT OF VIEW </b> Jason lies dead on the asphalt. For about two seconds. He <b> SLOWLY STANDS. </b> <b> RENNIE </b> desperately throws it into forward again, gripping the wheel and RACING FORWARD. <b> POINT OF VIEW FROM FRONT BUMPER (STUNT DRIVE) </b> Jason's standing there for one second, but the next moment he is LEAPING OUT OF THE WAY... <b> EXT. ABANDONED PARKING LOT (STUNT DRIVE) </b> ...and the squad car SMASHES THROUGH A CHAIN LINK FENCE, <b> FREEFALLING TO THE ABANDONED PARKING LOT BELOW. </b> <b> EXT. ALLEY #3 - CONTINUOUS (STUNT DRIVE) </b> as the car bottoms out, then swerves into a sharp right turn, racing down the alley. <b> POINT OF VIEW FROM FRONT BUMPER (STUNT DRIVE) </b> as Jason appears at the end of the alley, blocking their retreat. <b> INT. SQUAD CAR - CONTINUOUS </b> as Rennie stomps the brake pedal, jerking it into reverse... <b> EXT. ALLEY #3 - CONTINUOUS (STUNT DRIVE) </b> as she backs up, changes gears and races down an intersecting alley. <b> POINT OF VIEW FROM FRONT BUMPER (STUNT DRIVE) </b> speeding towards an escape when JASON POPS OUT AGAIN! He's everywhere all at once... <b> INT. SQUAD CAR - CONTINUOUS </b> slamming on the discs one more time, flooring it into reverse. <b> CLOSE ON TIRES - CONTINUOUS (SECOND UNIT) </b> as the squad car's rear tires smoke and spin, finally gripping pavement. <b> POINT OF VIEW OUT REAR WINDOW (STUNT DRIVE) </b> as we fly backwards...and JASON APPEARS BEHIND THEM!! <b> TIGHT ON REAR VIEW MIRROR </b> --Rennie's terrified face filling it, seeing that Jason is in back of them. <b> TIGHT ON REAR TIRES (SECOND UNIT) </b> as they screech to a halt one final time, rapidly rotating in the opposite direction and speeding out of frame. <b> INT. SQUAD CAR - CONTINUOUS </b> Rennie is almost maniacal now, her knuckles white around the vinyl wheel, her foot practically mashed through the floorboard. <b> MCCULLOCH </b> Rennie, for God's sake slow down!! She doesn't hear him, or anything for that matter. Her eyes remain straight ahead, never blinking. <b> RENNIE'S POINT OF VIEW (POST EFX) </b> There's a FIGURE standing in the distance. But it looks too small to be Jason. We RUSH TOWARDS IT, CHANGING INTO SLOW MOTION JUST BEFORE IMPACT. The figure is a dripping wet boy with a sinister smile. YOUNG JASON. <b> EXT. BRICK WALL - A SPLIT SECOND LATER (EFX) </b> as the front of the squad car RAMS THE BRICK WALL HEAD- <b> ON, THE HOOD BURSTING INTO FLAMES. </b> <b> ANOTHER ANGLE </b> as the front passenger door is shoved open by Sean, who drags out Rennie. McCulloch follows close behind, helping Sean carry her away from the wreckage, over by a row of old oil drums filled with slime and rainwater. Then it suddenly hits Sean... <b> SEAN </b> Miss Van Deusen... He takes two steps back to the car when: <b> BOOM! (EFX) </b> The squad car interior is ENGULFED IN A BALL OF FLAMES. <b> RENNIE </b> opens her dazed eyes, seeing Miss Van Deusen's body charring inside the wreckage. It's incomprehensible. She numbly gets to her feet, stepping towards it. Something makes her hesitate: she peers down at the asphalt... <b> EXT. ASPHALT - RENNIE'S POINT OF VIEW (POST EFX) </b> A pool of gasoline has collected, flames dancing across its glassy surface. Suddenly a TINY ROWBOAT DISSOLVES IN, not unlike the lifeboat she was so afraid of. The rowboat glides across the surface of the burning gasoline, TWO PEOPLE RIDING IN IT. The flames and asphalt <b> SLOWLY FADE OUT AND GIVE WAY TO A SERENE LAKE. </b> <b> RENNIE'S FLASHBACK - CRYSTAL LAKE - DAY </b> Shimmering water, clouds and pine trees reflected in it. The rowboat floats into view. The two occupants are YOUNG RENNIE and MCCULLOCH. She's wearing a bathing suit and an innocent smile. And not an inkling of fear about the water. She stands, letting the sun soak into her. <b> YOUNG RENNIE </b> What a beautiful day. <b> MCCULLOCH </b> Perfect for a swim, isn't it? She frowns at him, looking away. <b> MCCULLOCH </b> You've been coming out here every summer for the last three years, young lady, and you still haven't learned how. <b> YOUNG RENNIE </b> I'll take some lessons this time. I promise. She bends over, splashing the water. <b> MCCULLOCH </b> That's what you said last year. I think the time for your first swimming lesson has just come. The splashing stops. <b> MCCULLOCH </b> You don't want to end up drowning like that Voorhees boy, do you? She's instantly tense. <b> MCCULLOCH </b> He never learned how either and he's still at the bottom of this lake. <b> YOUNG RENNIE </b> He is not. <b> MCCULLOCH </b> Oh, he is indeed. And ready to pull down anybody who falls in and can't swim. <b> YOUNG RENNIE </b> You're telling a lie. <b> MCCULLOCH </b> Am I? Let's find out. ...And quicker than she's able to react to it, MCCULLOCH <b> PUSHES HER OVERBOARD. </b> <b> SPLASH! </b> as Rennie's body violently disrupts the calm surface. She immediately begins to flounder. McCulloch calmly leans over the edge. <b> MCCULLOCH </b> Better swim before Jason drags you down, Rennie. Come on, you can do it... ...but Rennie thrashes in the water, struggling to keep from sinking under the surface. <b> RENNIE'S POINT OF VIEW </b> Her uncle's face blurs and clears as water splashes her eyes. <b> YOUNG RENNIE </b> I...I can't... <b> MCCULLOCH </b> You can and you will! Swim, Rennie! <b> RENNIE </b> is too panicked to obey. <b> YOUNG RENNIE </b> Hhhhelp...me.... She coughs on some water then disappears... <b> UNDERWATER (TANK) </b> The world above her ceases to exist, murky lake water taking over. Rennie looks-down, and to her horror... <b> RENNIE'S POINT OF VIEW (TANK) </b> Young Jason is grabbing her ankle and dragging her down. The whole image BURSTS INTO FLAMES and we: <b> DISSOLVE BACK TO: </b> <b> EXT. ASPHALT - NIGHT </b> as the gasoline continues to burn, the rowboat gone. ADJUST to find RENNIE'S FACE, the flames of the car wreckage flickering over her glassy eyes. She looks up at Miss Van Deusen's body one last time before: <b> ANGLE - SQUAD CAR (EFX) </b> The auto's fuel tank EXPLODES, SHRAPNEL FLYING <b> EVERYWHERE. </b> <b> EXT. ALLEY #4 - CONTINUOUS </b> She looks up at her uncle with knowing eyes. Eyes that tell him she's remembered everything. <b> RENNIE </b> You pushed me... <b> MCCULLOCH </b> (defensively) I was only trying to teach you. But I pulled you out, Rennie. I saved your life. Rennie just stares, incredulous. <b> SEAN </b> You son of a bitch... She lets it build until she's ready to explode...then: <b> RENNIE </b> He was down there!!! And Rennie runs off. McCulloch starts to follow but Sean grabs him, shoving him down. <b> SEAN </b> You keep away from her! Sean chases after Rennie. Camera methodically PANS BACK TO MCCULLOCH, crumpled on the ground. A very bitter man. He wipes his hands, getting ready to stand when THE SHADOW FALLS OVER HIM. His skin fades to porcelain white. <b> MCCULLOCH </b> You...are...NOT POSSIBLE. But possible, and actual, he is. A PAIR OF ROTTED ARMS <b> EXTEND DOWN, RIPPING HIM OUT OF FRAME. </b> <b> TRACKING WITH JASON </b> as the walking corpse lifts a screaming McCulloch over his head, carrying him over to one of the scum-filled OIL DRUMS, SHOVING HIM HEAD-FIRST INTO IT. Jason grips McCulloch's thrashing legs as bubbles rise to the surface of the slime, a pathetic gurgling reverberating out the drum. At last McCulloch's appendages go limp. Jason releases him, moving on. <b> EXT. ALLEY #5 - NIGHT </b> as Sean runs into view, glancing around, spotting Rennie, crouched against a crumbled brick wall. No tears...only hate. Sean sits down next to her. After several moments... <b> RENNIE </b> I was at school when they told me. 'Rennie, we have some very bad news... your parents have been killed in an auto accident.' Sean gently takes her hand, sharing her internal agony. <b> RENNIE </b> It seems like everybody I care about ends up... She can't finish. PUSH IN as Sean kisses her on the forehead, then makes her look into his eyes. <b> SEAN </b> Not this time. He caresses her face; it develops into a tender kiss. Finally she holds him back, letting it out. At the same time: <b> STALKING POINT OF VIEW </b> Somebody is creeping at a low angle towards them. <b> SEAN AND RENNIE </b> are lost in their shared quiet moment...until the GROWLING SOUND becomes audible. They look up, seeing: <b> TOBY </b> cautiously approaching them. Rennie stands, absolutely relieved. <b> RENNIE </b> Toby... She starts to move towards him and her dog SNARLS <b> VICIOUSLY, CROUCHING BACK IN FEAR. </b> <b> RENNIE </b> What's wrong, boy? Another protective growl, then: <b> CRASH! </b> as Jason stampedes through a stack of crates and garbage cans behind them. <b> SEAN, RENNIE AND TOBY </b> abruptly flee down the alley, Jason in mad pursuit. <b> EXT. ALLEY/SUBWAY ENTRANCE - NIGHT </b> as Rennie, Sean and the dog run straight towards us, Jason swiftly catching up. FAST TRACK WITH THEM over to a deserted, rain-slicked SUBWAY ENTRANCE. <b> INT. SUBWAY ENTRANCE - CONTINUOUS (EFX) </b> as they bang through the glass doors, sailing past us. Three beats later, JASON APPEARS, not bothering to open the door, STAMPEDING RIGHT THROUGH THE GLASS. <b> INT. SUBWAY STATION - ESCALATORS (N.Y.) </b> Sean, Rennie and Toby sail down the escalators past a few scattered COMMUTERS. Again, Jason appears, looming tall at the top. He starts down the "up" escalator. <b> JASON'S POINT OF VIEW (ICY.) </b> as an ELDERLY COUPLE rises toward us. Their reactions grow more bleak the closer we get, finally registering terror as we plow right through them. <b> ANGLE - SUBWAY TURNSTILES (ICY.) </b> Sean and Rennie hop over a metal turnstile, Toby crawling under it. A TICKET TAKER leans out his window, shouting at them. <b> TICKET TAKER </b> Hey! The teenagers are soon forgotten as JASON SMASHES THROUGH <b> THE TURNSTILE LIKE THE TERMINATOR, TEARING THE ALUMINUM </b> WHEEL RIGHT OFF ITS BASE. The Ticket Taker reacts speechlessly, deciding not to press his luck. <b> INT. SUBWAY PLATFORM - CONTINUOUS (N.Y.) </b> as Sean and Rennie slide up to the edge of the track pit, SEEING THE LIGHTS OF AN APPROACHING TRAIN which is taking too long to get there. <b> SEAN </b> Come on... ...but Jason arrives before the train. Toby barks and snarls, trying to protect them. Jason is unfazed. He treads toward them and: <b> DOG TOBY </b> leaps onto Jason, sinking his teeth into the monster's throat. Jason wrestles the animal into submission just as: <b> THE SUBWAY TRAIN </b> streaks into the station. A fraction of time later: <b> JASON </b> heaves the dog in front of the train. <b> RENNIE </b> shrieks in horror as Toby disappears inside the pit just as the train roars by. <b> ANGLE - ONLOOKERS </b> They're New Yorkers, but not callous enough to stomach this, quickly scattering. Even a group of severe SKINHEADS decide they can wait for the next train, quickly heading up the escalators after seeing Jason in action. <b> SEAN </b> makes Rennie look away, dragging her with him along the platform edge in retreat as Jason returns his attention to them. They reach the end of the platform, having no choice but to board the front car. <b> INT. SUBWAY TRAIN (N.Y.) </b> as the doors whoosh shut...but Jason PRIES THEM OPEN. The TRAIN ENGINEER glances back from his booth, seeing Jason making the improper entry. <b> TRAIN ENGINEER </b> Hey pal, you can't do that... A second later he's gotten a good look at Jason. It's too late for a retraction as JASON SAVAGELY JAMS HIS HEAD <b> INTO THE TRAIN CONSOLE. </b> <b> INSERT - TRAIN CONSOLE </b> as the Engineer's arm KNOCKS THE THROTTLE FORWARD... <b> EXT. SUBWAY STATION - CONTINUOUS (N.Y.) </b> ...and the train begins to move, racing into the black tunnel. <b> INT. SUBWAY TRAIN - NIGHT (N.Y.) </b> as Rennie and Sean run for their lives, arriving at the end of a car, jamming the separating doors open and entering the next car. Jason follows right behind. <b> INT. SUBWAY STATION - NIGHT (N.Y.) </b> as the train thunders through the station without stopping, baffling several waiting COMMUTERS. <b> INT. SUBWAY TRAIN - JASON'S POINT OF VIEW (N.Y.) </b> --seeing Sean and Rennie disappear through another connecting door. We storm our way through it into the next car right after them. A handful of TRAVELERS cower away from us. <b> INT. SUBWAY TUNNEL - NIGHT (N.Y.) </b> as the train rapidly speeds past us, showing no signs of slowing down. <b> INT. SUBWAY TRAIN - FINAL CAR (N.Y.) </b> as Sean and Rennie come through another set of separating doors, rushing through... finding they're in the last car. They look back, seeing Jason enter at the opposite end. The monster stalks forward. Sean's eyes dart around. He spots the EMERGENCY STOP CORD. HE LEAPS FOR <b> IT. </b> <b> EXT. SUBWAY TUNNEL - NIGHT (N.Y.) </b> ...and the train SCREECHES TO A HALT. <b> INT. SUBWAY TRAIN - CONTINUOUS (N.Y.) </b> The sudden stop throws Jason on his back. Sean throws the rear door open, jumping out with Rennie. <b> INT. SUBWAY TUNNEL - NIGHT (N.Y.) </b> as Sean and Rennie sprint down the center of the tracks toward the light of the next station, running out of strength. <b> INT. TIMES SQUARE STATION - NIGHT (N.Y.) </b> as they emerge from the darkness, up to the edge of the pit. Sean boosts Rennie up, starting to climb up himself when: <b> JASON </b> fires out from the tunnel, grabbing onto Sean's ankle. Rennie screams as Sean is dragged down...but he manages to latch onto a chain securing a garbage receptacle. Jason pulls harder, stretching Sean to his limit as Rennie watches helplessly. <b> RENNIE </b><b> NO!!! </b> <b> RENNIE </b> runs straight towards the track pit like a football punter, RECOILING WITH HER RIGHT LEG, KICKING JASON <b> SQUARELY IN THE FACE. </b> <b> JASON (EFX) </b> trips backwards and LANDS ON THE THIRD, ELECTRIFIED RAIL, RECEIVING TEN THOUSAND VOLTS. His body smokes and convulses, finally sizzling out. He appears to be terminated!!! <b> ANGLE - SEAN AND RENNIE </b> as they get to their feet, holding each other tight, looking down on the now-dead undead creature. <b> EXT. TIMES SQUARE - NIGHT (N.Y.) (CRANE SHOT) </b> as our heroes arise into the neon-filled big city wonderland, relieved to be alive, gazing around at the awesome spectacle known as Times Square. A huge DIGITAL CLOCK tells us it's a quarter to midnight. Sean wraps his arm around her. <b> SEAN </b> It's over, Rennie. It's finally over. Camera RISES ABOVE THEM, RACKING BACK TO THE SUBWAY EXIT. Guess who has just made an encore...with more energy than ever!!! <b> SEAN AND RENNIE </b> look all around them, having never been to a city as big as this. They finally turn far enough around to spot JASON in a series of three quick cuts, each one closer than the last. <b> SEAN </b> God...please no... But Jason keeps on coming. <b> RENNIE </b> Somebody help us!! He's going to kill us!!! But the heavy Times Square foot traffic ignores her, bustling onward. Rennie and Sean have no choice but to flee again. <b> JASON </b> shoves his way through the preoccupied pedestrians; they've certainly seen weirder characters than him here. He moves past a group of STREET URCHINS listening to some rap from their ghetto blaster. His foot obliterates their stereo system with one stride. They instantly pull out switchblades and chains. <b> STREET URCHIN </b> You're dead meat, slime bag. Jason stops, turning around, towering over the kids. He has blood and gore caked everywhere, his skin charred from the electrocution. Jason starts to remove his mask, facing them squarely. <b> TIGHT ON STREET URCHINS </b> as Jason's mask comes off out-of-frame. Their tough faces turn to putty, scared completely shitless. <b> STREET URCHIN </b> Hey man, it's cool, it's cool... They turn tail and race like the wind. Jason steps forward so that we're looking at the back of his head, never seeing his naked face. He slips his hockey mask on again, turns into a CLOSE UP, then exits. <b> INT. TIMES SQUARE DINER - NIGHT </b> filled with noise, smoke and derelicts. A tough, redheaded WAITRESS with a thick Brooklyn accent stands behind the countertop, a wall of mirrors behind her. The front door bangs open with the entrance of Sean and Rennie, rushing up to the waitress. <b> SEAN </b> (out of breath) You have to call the police... <b> RENNIE </b> Please, hurry... A telephone sits right next to her, but this is New York. <b> WAITRESS </b> There's a pay phone in back. They start to run. <b> WAITRESS </b> ...but it's broken. <b> RENNIE </b> You don't understand -- there's a maniac trying to kill us!!! <b> WAITRESS </b> (blase) Welcome to New York. There's no time for further response as JASON CRASHES <b> THROUGH THE DINER DOOR, MOWING A PATH STRAIGHT TOWARDS </b> THEM. Sean and Rennie run out the back as the Waitress eyes Jason with complete disbelief. <b> ANOTHER ANGLE </b> as the BURLY CHEF comes out to confront him. Jason FLINGS <b> HIM HEAD FIRST INTO THE JUKEBOX. </b> <b> THE WAITRESS </b> picks up the telephone, really pissed off. <b> A BIKER </b> climbs off his counter stool, revealing a HUGE BOWIE KNIFE. Jason plows straight for him and the Biker STABS JASON IN THE HEART. Jason has little reaction, pulling it out, tossing it aside. The Biker's face goes wan, backing away. <b> THE WAITRESS </b> stops in mid-dial. Fear is starting to register now. <b> JASON </b> lifts the very large man and EFFORTLESSLY HEAVES HIM INTO <b> THE MIRROR OVER THE COUNTER. </b> <b> THE WAITRESS </b> feels the phone receiver slipping from her grasp, her mouth trembling. She backs away from the beast as far as she can. Jason has no time to waste on her, trampling out the back after Rennie and Sean as the other patrons shrink from him. <b> INT. REAR OF DINER - SAME TIME </b> as Sean fumbles to unlock three deadbolts and two chains, finally getting the back door open and springing into: <b> EXT. DEAD END ALLEY - NIGHT </b> They run about ten yards before realizing the alley is a dead end. Sean and Rennie start to head back the other way when JASON MOWS OUT FROM THE DINER DOOR. Their vision scatters everywhere in search of a retreat... <b> RENNIE </b> Look! She's spotted a MANHOLE COVER, slightly ajar. They haven't the luxury of thinking about it, Sean sliding the cover back as Jason comes forth. <b> INT. SEWER - ENTRANCE CHAMBER - NIGHT </b> as they descend into hell...a massive chamber consisting of tall columns, slimy catacombs and three feet of stagnant water. Their alternatives are nil; Sean and Rennie join hands, wading through the swill, splashing deeper into the labyrinth. <b> ANGLE UP STAIRS </b> as the dim streetlight glowing in the above world is eclipsed by JASON, making his way down after them. <b> INT. TUNNEL #1 - NIGHT </b> An oval tunnel slanted downward into pitch blackness. Dim overhead lights illuminate salt deposits and eery rust formations. Rennie and Sean appear at the far end, wading from the sewage as the tunnel rises toward us. <b> TRACKING SHOT </b> as they come forward at a brisk but cautious pace, strangers in a very strange land. <b> ANGLE - THEIR FEET </b> sloshing through the slime. All is silent until Sean's foot TRIPS OVER A BARREL labeled HUGHES CHEMICAL PLANT. A vaporous green substance oozes out the rusty end of the container, sizzling on the around. <b> SEAN AND RENNIE </b> carefully sidestep it, continuing on. They make it another ten yards when A FIGURE LEAPS OUT FROM AN ALCOVE, GRIPPING A HUGE WRENCH. Rennie's scream echoes through the tunnel. <b> REVERSE ANGLE </b> ...but it's a middle-aged SANITATION ENGINEER who lowers the wrench, as frightened as they are. <b> SANITATION ENGINEER </b> What the hell are you kids doing down here? <b> SEAN </b> Can you help us get out?? <b> SANITATION ENGINEER </b> I sure can and we don't have a minute to waste. He begins quickly packing up his tools. <b> SEAN </b> What do you mean? <b> SANITATION ENGINEER </b> Toxic waste, son. This sewer floods out with the stuff on the 13th of every month, right at midnight. (checks watch) And that's less than ten minutes from now. Rennie looks down the dark tunnels in all directions, swallowing hard. <b> SANITATION ENGINEER </b> Follow me. He clicks on his high powered flashlight and quickly leads them down: <b> INT. TUNNEL #2 </b> ...no less threatening than the one they just left. When they pass a lightless intersecting corridor, JASON EJECTS <b> HIMSELF FROM IT, TACKLING THE SANITATION ENGINEER AND </b><b> SEAN. </b> <b> THE FLASHLIGHT </b> rolls through the muck, its beam splashing erratically across the polluted walls. <b> THE SANITATION ENGINEER </b> begins BASHING JASON'S HEAD IN WITH HIS WRENCH but the monster drags the kicking and screaming man into TUNNEL <b> #3. </b> <b> RENNIE </b> tries to help up Sean but he's been knocked into the opposite wall, barely conscious. <b> SEAN </b> Run, Rennie... She's struck with indecisive shock, looking into Tunnel #3, seeing: <b> A GRUESOME SHADOW ON THE WALL </b> Jason arches his back with wrench in hand, hammering it over and over into the Sanitation Engineer's skull. <b> RENNIE </b> backs away but does not run. The time has come to face her fears. <b> ANGLE - SHADOW ON TUNNEL #3 WALL </b> as Jason takes one more vengeful stroke, finishing him off. He steps from Tunnel #3 with the scarlet-coated tool, his shadow becoming flesh. He moves straight for Sean, who has no hope for escape. Jason cocks the wrench over Sean's skull...and suddenly his hockey mask is SPLASHED WITH A BRIGHT LIGHT. Jason stops, turning directly into it. <b> JASON'S POINT OF VIEW </b> Rennie is blinding us with the sanitation Engineer's flashlight, giving us only brief glimpses of herself in the reflective wet surroundings. <b> RENNIE </b> You never got me in the lake, Jason. And you're not going to get me now either. Her voice is defiant. She carefully backstops, the irritating light never leaving us. <b> JASON </b> has been sufficiently taunted. He moves after her. <b> JASON'S POINT OF VIEW </b> as the bright beam leaves our eyes, Rennie dashing down the intersecting tunnel (#1). <b> TIGHT ON JASON'S FEET </b> stomping through the sludge, picking up speed. He's wanted to kill Rennie most of all. <b> INT. TUNNEL #L </b> as Rennie dashes up to the HUGHES CHEMICAL DRUM Sean tripped over, using the back end of the flashlight to crush in the can's rusted lid. The metal is flimsy but still resists her blows. She frantically hammers harder. <b> INT. TUNNEL #2 - TRACKING WITH JASON </b> He's moving like a freight train now, an addict rolling after his fix. <b> INSERT - CHEMICAL DRUM </b> as the butt of the flashlight dents the metal, ultimately causing it to cave in. <b> INT. TUNNEL INTERSECTION - JASON'S POINT OF VIEW </b> --Looking through his unblinking eyes, whipping into Tunnel #1...where we catch a fleeting glimpse of Rennie flinging the contents of the oil drum. A half second later a WAVE OF GRAY/GREEN LIQUID FLIES AT US... <b> TIGHT ON JASON (SLOW MOTION) </b> and his hockey mask is SPLASHED WITH TOXIC WASTE, SEEPING INTO HIS MASK'S EYE SLITS. He careens back as if her were a rabid dog receiving a load of point-blank buckshot. <b> RENNIE </b> drops the can, fumbling for the flashlight again. <b> CLOSE UP - JASON (EFX) </b> as the radiant flashlight beam finds his mask, the plastic beginning to bubble and melt. RUSH INTO A TIGHT <b> CLOSE UP AS JASON TEARS OFF HIS MASK, EXPOSING HIS </b> HIDEOUS FACE: rotted flesh, some of it sizzling from the chemical. Worms slithering out his nostrils. And his eyes...or lack thereof. They're like two raw quail eggs frying in liquid green pollutant...and the yolks just broke, running down his face. <b> CLOSE ON FLASHLIGHT </b> as the beam begins to waver in her quivering grasp. RISE TO FIND RENNIE'S FACE, reacting to the stomach-turning sight of Jason's visage. She grabs hold of her senses and <b> RUNS. </b> <b> ANOTHER ANGLE </b> as Rennie skirts past the blinded creature: WHIP PAN WITH HER as she turns down Tunnel #2, heading back toward Sean. CONTINUE TO QUICKLY PAN AROUND until we've come around 360 degrees and are back on JASON, in no way ready to give up. He staggers after Rennie. <b> INT. TUNNEL #2 </b> as Rennie skids up to Sean, still dazed. She grabs him, shaking hard. <b> RENNIE </b> Get up, Sean!!! His eyes blink, only half coherent. Then an inconceivable terror registers in her ears...A LOW, DEEP RUMBLING SOUND, COMING FROM UP AHEAD. Her head jerks in the direction of her planned retreat: <b> RENNIE'S POINT OF VIEW </b> An ominously empty tunnel, soon to be filled with the unthinkable. The sound of RUSHING LIQUID is growing at leaps and bounds. <b> TIGHT ON RENNIE </b> as her trembling chin rises, looking at: <b> ANGLE - TUNNEL #3 CEILING (EFX) </b> The dim overhead lights are beginning to vibrate from the approaching flood. <b> RENNIE </b> rotates her head and sees: <b> JASON </b> vision or no vision, he is lurching towards her relentlessly. She is literally sandwiched between hell and high water. <b> RENNIE </b> drags Sean to his feet with the strength of a possessed woman, pulling him over to a SERVICE LADDER attached to the intersecting alcove wall. <b> RENNIE </b> (screaming) Climb!!! She shoves him up it from below, Sean summoning everything he's got to obey her. Rennie shoots a stare back down the tunnel... <b> RENNIE'S POINT OF VIEW (EFX) </b> The overhead lights are banging around like an earthquake has just hit; the liquid will be arriving any second. Her vision WHIP PANS 180 DEGREES TO FIND JASON APPROACHING FROM THE OPPOSITE END, groping around with his scaly arms like the claws of a roto-tiller. <b> ANGLE - LADDER </b> as Rennie starts up after Sean, looking down and seeing: <b> JASON </b> within ten feet of them, shifting directly for the ladder like he's working on some kind of radar. <b> RENNIE </b> slips on the rusty ladder, regaining her footing. and rushing higher. She takes her final glance into the tunnel, the ultimate horror registering in her corneas as she sees: <b> INT. TUNNEL #3 (MODEL EFX) </b> A million gallons of green-brown toxic waste splash into the far intersection, FILLING THE TUNNEL, FLOODING <b> STRAIGHT FOR CAMERA. </b> <b> JASON </b> has just started to climb the ladder when the wind and smell of the rushing toxic waste bombards him. His decomposed head swivels to face: <b> INT. TUNNEL #3 (MODEL EFX) </b> Tons of lethal sewage, stopping for no one. Arriving in seconds. <b> JASON'S FINAL CLOSE UP (EFX/FIBER OPTIC LENS) </b> He doesn't need vision to confirm what his other senses already know. Jason's mouth begins to quaver...AND THE <b> FIRST WORDS HE HAS EVER SPOKEN COME OUT, IN THE VOICE OF </b><b> AN EIGHT YEAR OLD BOY: </b> <b> JASON </b> Mmmmmmmmmommy...DON'T LET ME DROWN, <b> MOMMY... </b> Camera speeds toward his gaping mouth and DOWN HIS THROAT as lightning arcs off his mucous covered insides. We sink deeper into his guts, fire and smoke flaring into our eves, eventually coming to a WELL IN THE PIT OF HIS STOMACH, FILLED WITH BLOOD...and EIGHT YEAR OLD JASON IS <b> DROWNING IN IT. </b> <b> YOUNG JASON </b> Hhhhelp me.... A split second later: <b> EXT. TUNNEL #3 (EFX) (SLOW MOTION) </b> The wall of deadly toxic liquid ENGULFS JASON. <b> INT. TUNNEL #3 - ON RENNIE AND SEAN (EFX) </b> The powerful flood thrashes the ladder about two inches below Rennie's feet, the force of it fiercely shaking their rusty support. They are clinging to the ladder with their eyes squeezed shut. Praying for survival. <b> INT. TUNNEL #3 (MODEL EFX) </b> We are drowning in a chunky cloud of sewage, rushing over and under us. <b> EXT. TIMES SQUARE - NIGHT (EFX) </b> The digital clock we saw earlier abruptly CHIMES <b> MIDNIGHT, HUGE BOLTS OF LIGHTNING CRACKING OVER </b><b> MANHATTAN. </b> <b> ANGLE - SEAN AND RENNIE (EFX) </b> as the sewage level begins to drop. Rennie opens her eyes, glancing straight down and seeing. <b> RENNIE'S POINT OF VIEW (EFX) </b> The ladder beneath them reappears...which gives way to a PAIR OF HANDS GRIPPING THE BOTTOM RUNG. The liquid drops further, unshrouding the now-dead corpse of EIGHT YEAR OLD JASON. He's a relatively normal looking boy, probably the way he looked back in 1957...right when he drowned in Crystal Lake. Jason Voorhees has finally been put to rest. <b> EXT. TIMES SQUARE - NIGHT (N.Y.) </b> Rennie and Sean stagger out from a side street, holding each other up...relief etched in their matured faces. <b> SEAN </b> I hear there's a statue here that's 22 stories tall. Rennie would smile if she could. She kisses his cheek. They amble on. <b> STALKING POINT OF VIEW </b> ...coming out from another alley, creeping up behind them through a crowd of pedestrians. About the height of a small child. <b> RENNIE AND SEAN </b> walk arm in arm, exhausted and oblivious to their pursuer. But something, some innate perception causes Rennie to slow...and stop. Her eyes register a horrid fear and she WHIPS AROUND TO FACE... <b> TOBY! </b> Limping on all fours, filthy with grease-matted fur. The whimpering dog crawls up to her, Rennie bending down, hugging her animal like she'll never let go. <b> RENNIE </b> Oh Toby... <b> HIGH ANGLE CRANE SHOT (N.Y.) </b> as Sean bends down too, ruffling the dog's fur, standing again with Rennie. The three survivors enter the collage of pedestrians, bright lights and skyscrapers. It is finally over. <b> FADE OUT. </b> <b> THE END </b> </pre> </pre><br> <table width="85%" border="0" align="center" cellpadding="5" cellspacing="0" class="body" style="BORDER-TOP: #000000 1px solid; BORDER-RIGHT: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid;"> <tr> <td align=center> <td><h1>Friday the 13th Part VIII: Jason Takes Manhattan</h1><br><br> <b>Writers</b> : &nbsp;&nbsp;<a href="/writer.php?w=Rob Hedden" title="Scripts by Rob Hedden">Rob Hedden</a><br> <b>Genres</b> : &nbsp;&nbsp;<a href="/genre/Horror" title="Horror Scripts">Horror</a><br><br><br> <a href="/Movie Scripts/Friday the 13th Part VIII: Jason Takes Manhattan Script.html#comments" title="Friday the 13th Part VIII: Jason Takes Manhattan comments">User Comments</a> </td> </table> <br><br> <div align="center"> <a href="https://www.imsdb.com" title="Internet Movie Script Database"><img src="/images/lilbutton.gif" style="border: 1px solid black;" alt="Internet Movie Script Database" border=1><br> Back to IMSDb</a> </div><br> <br><br> </tr> </table> <br><br> </table> <table width="99%" border="0" cellspacing="0" cellpadding="0" class="body"> <tr> <td background="/images/reel.gif" height="13" colspan="2"> </table> <div align="center"> <a href="https://www.imsdb.com" title="Internet Movie Script Database (IMSDb)">Index</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/submit" title="Submit scripts">Submit</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/links" title="Other sites">Links</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/link to us" title="Link to IMSDb">Link to us</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/feeds" title="IMSDb RSS Feeds">RSS Feeds</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/disclaimer">Disclaimer</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="/privacy">Privacy policy</a> </div> <br /> </body> </html> Question: Who is responsible for Rennie's fear of water? Answer: McCulloch
{ "task_name": "narrativeqa" }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver12; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import com.google.common.collect.ImmutableSet; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFDescStatsReplyVer12 implements OFDescStatsReply { private static final Logger logger = LoggerFactory.getLogger(OFDescStatsReplyVer12.class); // version: 1.2 final static byte WIRE_VERSION = 3; final static int LENGTH = 1072; private final static long DEFAULT_XID = 0x0L; private final static Set<OFStatsReplyFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsReplyFlags>of(); private final static String DEFAULT_MFR_DESC = ""; private final static String DEFAULT_HW_DESC = ""; private final static String DEFAULT_SW_DESC = ""; private final static String DEFAULT_SERIAL_NUM = ""; private final static String DEFAULT_DP_DESC = ""; // OF message fields private final long xid; private final Set<OFStatsReplyFlags> flags; private final String mfrDesc; private final String hwDesc; private final String swDesc; private final String serialNum; private final String dpDesc; // // Immutable default instance final static OFDescStatsReplyVer12 DEFAULT = new OFDescStatsReplyVer12( DEFAULT_XID, DEFAULT_FLAGS, DEFAULT_MFR_DESC, DEFAULT_HW_DESC, DEFAULT_SW_DESC, DEFAULT_SERIAL_NUM, DEFAULT_DP_DESC ); // package private constructor - used by readers, builders, and factory OFDescStatsReplyVer12(long xid, Set<OFStatsReplyFlags> flags, String mfrDesc, String hwDesc, String swDesc, String serialNum, String dpDesc) { if(flags == null) { throw new NullPointerException("OFDescStatsReplyVer12: property flags cannot be null"); } if(mfrDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property mfrDesc cannot be null"); } if(hwDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property hwDesc cannot be null"); } if(swDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property swDesc cannot be null"); } if(serialNum == null) { throw new NullPointerException("OFDescStatsReplyVer12: property serialNum cannot be null"); } if(dpDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property dpDesc cannot be null"); } this.xid = xid; this.flags = flags; this.mfrDesc = mfrDesc; this.hwDesc = hwDesc; this.swDesc = swDesc; this.serialNum = serialNum; this.dpDesc = dpDesc; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public String getMfrDesc() { return mfrDesc; } @Override public String getHwDesc() { return hwDesc; } @Override public String getSwDesc() { return swDesc; } @Override public String getSerialNum() { return serialNum; } @Override public String getDpDesc() { return dpDesc; } public OFDescStatsReply.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFDescStatsReply.Builder { final OFDescStatsReplyVer12 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsReplyFlags> flags; private boolean mfrDescSet; private String mfrDesc; private boolean hwDescSet; private String hwDesc; private boolean swDescSet; private String swDesc; private boolean serialNumSet; private String serialNum; private boolean dpDescSet; private String dpDesc; BuilderWithParent(OFDescStatsReplyVer12 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFDescStatsReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public OFDescStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public String getMfrDesc() { return mfrDesc; } @Override public OFDescStatsReply.Builder setMfrDesc(String mfrDesc) { this.mfrDesc = mfrDesc; this.mfrDescSet = true; return this; } @Override public String getHwDesc() { return hwDesc; } @Override public OFDescStatsReply.Builder setHwDesc(String hwDesc) { this.hwDesc = hwDesc; this.hwDescSet = true; return this; } @Override public String getSwDesc() { return swDesc; } @Override public OFDescStatsReply.Builder setSwDesc(String swDesc) { this.swDesc = swDesc; this.swDescSet = true; return this; } @Override public String getSerialNum() { return serialNum; } @Override public OFDescStatsReply.Builder setSerialNum(String serialNum) { this.serialNum = serialNum; this.serialNumSet = true; return this; } @Override public String getDpDesc() { return dpDesc; } @Override public OFDescStatsReply.Builder setDpDesc(String dpDesc) { this.dpDesc = dpDesc; this.dpDescSet = true; return this; } @Override public OFDescStatsReply build() { long xid = this.xidSet ? this.xid : parentMessage.xid; Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : parentMessage.flags; if(flags == null) throw new NullPointerException("Property flags must not be null"); String mfrDesc = this.mfrDescSet ? this.mfrDesc : parentMessage.mfrDesc; if(mfrDesc == null) throw new NullPointerException("Property mfrDesc must not be null"); String hwDesc = this.hwDescSet ? this.hwDesc : parentMessage.hwDesc; if(hwDesc == null) throw new NullPointerException("Property hwDesc must not be null"); String swDesc = this.swDescSet ? this.swDesc : parentMessage.swDesc; if(swDesc == null) throw new NullPointerException("Property swDesc must not be null"); String serialNum = this.serialNumSet ? this.serialNum : parentMessage.serialNum; if(serialNum == null) throw new NullPointerException("Property serialNum must not be null"); String dpDesc = this.dpDescSet ? this.dpDesc : parentMessage.dpDesc; if(dpDesc == null) throw new NullPointerException("Property dpDesc must not be null"); // return new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); } } static class Builder implements OFDescStatsReply.Builder { // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsReplyFlags> flags; private boolean mfrDescSet; private String mfrDesc; private boolean hwDescSet; private String hwDesc; private boolean swDescSet; private String swDesc; private boolean serialNumSet; private String serialNum; private boolean dpDescSet; private String dpDesc; @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFDescStatsReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public OFDescStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public String getMfrDesc() { return mfrDesc; } @Override public OFDescStatsReply.Builder setMfrDesc(String mfrDesc) { this.mfrDesc = mfrDesc; this.mfrDescSet = true; return this; } @Override public String getHwDesc() { return hwDesc; } @Override public OFDescStatsReply.Builder setHwDesc(String hwDesc) { this.hwDesc = hwDesc; this.hwDescSet = true; return this; } @Override public String getSwDesc() { return swDesc; } @Override public OFDescStatsReply.Builder setSwDesc(String swDesc) { this.swDesc = swDesc; this.swDescSet = true; return this; } @Override public String getSerialNum() { return serialNum; } @Override public OFDescStatsReply.Builder setSerialNum(String serialNum) { this.serialNum = serialNum; this.serialNumSet = true; return this; } @Override public String getDpDesc() { return dpDesc; } @Override public OFDescStatsReply.Builder setDpDesc(String dpDesc) { this.dpDesc = dpDesc; this.dpDescSet = true; return this; } // @Override public OFDescStatsReply build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS; if(flags == null) throw new NullPointerException("Property flags must not be null"); String mfrDesc = this.mfrDescSet ? this.mfrDesc : DEFAULT_MFR_DESC; if(mfrDesc == null) throw new NullPointerException("Property mfrDesc must not be null"); String hwDesc = this.hwDescSet ? this.hwDesc : DEFAULT_HW_DESC; if(hwDesc == null) throw new NullPointerException("Property hwDesc must not be null"); String swDesc = this.swDescSet ? this.swDesc : DEFAULT_SW_DESC; if(swDesc == null) throw new NullPointerException("Property swDesc must not be null"); String serialNum = this.serialNumSet ? this.serialNum : DEFAULT_SERIAL_NUM; if(serialNum == null) throw new NullPointerException("Property serialNum must not be null"); String dpDesc = this.dpDescSet ? this.dpDesc : DEFAULT_DP_DESC; if(dpDesc == null) throw new NullPointerException("Property dpDesc must not be null"); return new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFDescStatsReply> { @Override public OFDescStatsReply readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 3 byte version = bb.readByte(); if(version != (byte) 0x3) throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got="+version); // fixed value property type == 19 byte type = bb.readByte(); if(type != (byte) 0x13) throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got="+type); int length = U16.f(bb.readShort()); if(length != 1072) throw new OFParseError("Wrong length: Expected=1072(1072), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property statsType == 0 short statsType = bb.readShort(); if(statsType != (short) 0x0) throw new OFParseError("Wrong statsType: Expected=OFStatsType.DESC(0), got="+statsType); Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer12.readFrom(bb); // pad: 4 bytes bb.skipBytes(4); String mfrDesc = ChannelUtils.readFixedLengthString(bb, 256); String hwDesc = ChannelUtils.readFixedLengthString(bb, 256); String swDesc = ChannelUtils.readFixedLengthString(bb, 256); String serialNum = ChannelUtils.readFixedLengthString(bb, 32); String dpDesc = ChannelUtils.readFixedLengthString(bb, 256); OFDescStatsReplyVer12 descStatsReplyVer12 = new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", descStatsReplyVer12); return descStatsReplyVer12; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFDescStatsReplyVer12Funnel FUNNEL = new OFDescStatsReplyVer12Funnel(); static class OFDescStatsReplyVer12Funnel implements Funnel<OFDescStatsReplyVer12> { private static final long serialVersionUID = 1L; @Override public void funnel(OFDescStatsReplyVer12 message, PrimitiveSink sink) { // fixed value property version = 3 sink.putByte((byte) 0x3); // fixed value property type = 19 sink.putByte((byte) 0x13); // fixed value property length = 1072 sink.putShort((short) 0x430); sink.putLong(message.xid); // fixed value property statsType = 0 sink.putShort((short) 0x0); OFStatsReplyFlagsSerializerVer12.putTo(message.flags, sink); // skip pad (4 bytes) sink.putUnencodedChars(message.mfrDesc); sink.putUnencodedChars(message.hwDesc); sink.putUnencodedChars(message.swDesc); sink.putUnencodedChars(message.serialNum); sink.putUnencodedChars(message.dpDesc); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFDescStatsReplyVer12> { @Override public void write(ByteBuf bb, OFDescStatsReplyVer12 message) { // fixed value property version = 3 bb.writeByte((byte) 0x3); // fixed value property type = 19 bb.writeByte((byte) 0x13); // fixed value property length = 1072 bb.writeShort((short) 0x430); bb.writeInt(U32.t(message.xid)); // fixed value property statsType = 0 bb.writeShort((short) 0x0); OFStatsReplyFlagsSerializerVer12.writeTo(bb, message.flags); // pad: 4 bytes bb.writeZero(4); ChannelUtils.writeFixedLengthString(bb, message.mfrDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.hwDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.swDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.serialNum, 32); ChannelUtils.writeFixedLengthString(bb, message.dpDesc, 256); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFDescStatsReplyVer12("); b.append("xid=").append(xid); b.append(", "); b.append("flags=").append(flags); b.append(", "); b.append("mfrDesc=").append(mfrDesc); b.append(", "); b.append("hwDesc=").append(hwDesc); b.append(", "); b.append("swDesc=").append(swDesc); b.append(", "); b.append("serialNum=").append(serialNum); b.append(", "); b.append("dpDesc=").append(dpDesc); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFDescStatsReplyVer12 other = (OFDescStatsReplyVer12) obj; if( xid != other.xid) return false; if (flags == null) { if (other.flags != null) return false; } else if (!flags.equals(other.flags)) return false; if (mfrDesc == null) { if (other.mfrDesc != null) return false; } else if (!mfrDesc.equals(other.mfrDesc)) return false; if (hwDesc == null) { if (other.hwDesc != null) return false; } else if (!hwDesc.equals(other.hwDesc)) return false; if (swDesc == null) { if (other.swDesc != null) return false; } else if (!swDesc.equals(other.swDesc)) return false; if (serialNum == null) { if (other.serialNum != null) return false; } else if (!serialNum.equals(other.serialNum)) return false; if (dpDesc == null) { if (other.dpDesc != null) return false; } else if (!dpDesc.equals(other.dpDesc)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((flags == null) ? 0 : flags.hashCode()); result = prime * result + ((mfrDesc == null) ? 0 : mfrDesc.hashCode()); result = prime * result + ((hwDesc == null) ? 0 : hwDesc.hashCode()); result = prime * result + ((swDesc == null) ? 0 : swDesc.hashCode()); result = prime * result + ((serialNum == null) ? 0 : serialNum.hashCode()); result = prime * result + ((dpDesc == null) ? 0 : dpDesc.hashCode()); return result; } }
{ "task_name": "lcc" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL { // Known shortcomings: // - Escaping identifier names is missing (special characters and ILASM identifier names) // - Array bounds in signatures missing // - Custom modifiers and PINNED constraint not decoded in signatures // - Calling conventions in signatures not decoded // - Vararg signatures // - Floating point numbers are not represented in roundtrippable format /// <summary> /// Helper struct to disassemble IL instructions into a textual representation. /// </summary> public struct ILDisassember { private byte[] _ilBytes; private MethodIL _methodIL; private ILTypeNameFormatter _typeNameFormatter; private int _currentOffset; public ILDisassember(MethodIL methodIL) { _methodIL = methodIL; _ilBytes = methodIL.GetILBytes(); _currentOffset = 0; _typeNameFormatter = null; } #region Type/member/signature name formatting private ILTypeNameFormatter TypeNameFormatter { get { if (_typeNameFormatter == null) { // Find the owning module so that the type name formatter can remove // redundant assembly name qualifiers in type names. TypeDesc owningTypeDefinition = _methodIL.OwningMethod.OwningType; ModuleDesc owningModule = owningTypeDefinition is MetadataType ? ((MetadataType)owningTypeDefinition).Module : null; _typeNameFormatter = new ILTypeNameFormatter(owningModule); } return _typeNameFormatter; } } public void AppendType(StringBuilder sb, TypeDesc type, bool forceValueClassPrefix = true) { // Types referenced from the IL show as instantiated over generic parameter. // E.g. "initobj !0" becomes "initobj !T" TypeDesc typeInContext = type.InstantiateSignature( _methodIL.OwningMethod.OwningType.Instantiation, _methodIL.OwningMethod.Instantiation); if (typeInContext.HasInstantiation || forceValueClassPrefix) this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, typeInContext); else this.TypeNameFormatter.AppendName(sb, typeInContext); } private void AppendOwningType(StringBuilder sb, TypeDesc type) { // Special case primitive types: we don't want to use short names here if (type.IsPrimitive || type.IsString || type.IsObject) _typeNameFormatter.AppendNameForNamespaceTypeWithoutAliases(sb, (MetadataType)type); else AppendType(sb, type, false); } private void AppendMethodSignature(StringBuilder sb, MethodDesc method) { // If this is an instantiated generic method, the formatted signature should // be uninstantiated (e.g. "void Foo::Bar<int>(!!0 param)", not "void Foo::Bar<int>(int param)") MethodSignature signature = method.GetMethodDefinition().Signature; AppendSignaturePrefix(sb, signature); sb.Append(' '); AppendOwningType(sb, method.OwningType); sb.Append("::"); sb.Append(method.Name); if (method.HasInstantiation) { sb.Append('<'); for (int i = 0; i < method.Instantiation.Length; i++) { if (i != 0) sb.Append(", "); _typeNameFormatter.AppendNameWithValueClassPrefix(sb, method.Instantiation[i]); } sb.Append('>'); } sb.Append('('); AppendSignatureArgumentList(sb, signature); sb.Append(')'); } private void AppendMethodSignature(StringBuilder sb, MethodSignature signature) { AppendSignaturePrefix(sb, signature); sb.Append('('); AppendSignatureArgumentList(sb, signature); sb.Append(')'); } private void AppendSignaturePrefix(StringBuilder sb, MethodSignature signature) { if (!signature.IsStatic) sb.Append("instance "); this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature.ReturnType); } private void AppendSignatureArgumentList(StringBuilder sb, MethodSignature signature) { for (int i = 0; i < signature.Length; i++) { if (i != 0) sb.Append(", "); this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature[i]); } } private void AppendFieldSignature(StringBuilder sb, FieldDesc field) { this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, field.FieldType); sb.Append(' '); AppendOwningType(sb, field.OwningType); sb.Append("::"); sb.Append(field.Name); } private void AppendStringLiteral(StringBuilder sb, string s) { sb.Append('"'); for (int i = 0; i < s.Length; i++) { if (s[i] == '\\') sb.Append("\\\\"); else if (s[i] == '\t') sb.Append("\\t"); else if (s[i] == '"') sb.Append("\\\""); else if (s[i] == '\n') sb.Append("\\n"); else sb.Append(s[i]); } sb.Append('"'); } private void AppendToken(StringBuilder sb, int token) { object obj = _methodIL.GetObject(token); if (obj is MethodDesc) AppendMethodSignature(sb, (MethodDesc)obj); else if (obj is FieldDesc) AppendFieldSignature(sb, (FieldDesc)obj); else if (obj is MethodSignature) AppendMethodSignature(sb, (MethodSignature)obj); else if (obj is TypeDesc) AppendType(sb, (TypeDesc)obj, false); else { Debug.Assert(obj is string, "NYI: " + obj.GetType()); AppendStringLiteral(sb, (string)obj); } } #endregion #region Instruction decoding private byte ReadILByte() { return _ilBytes[_currentOffset++]; } private UInt16 ReadILUInt16() { UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } private UInt32 ReadILUInt32() { UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } private int ReadILToken() { return (int)ReadILUInt32(); } private ulong ReadILUInt64() { ulong value = ReadILUInt32(); value |= (((ulong)ReadILUInt32()) << 32); return value; } private unsafe float ReadILFloat() { uint value = ReadILUInt32(); return *(float*)(&value); } private unsafe double ReadILDouble() { ulong value = ReadILUInt64(); return *(double*)(&value); } public static void AppendOffset(StringBuilder sb, int offset) { sb.Append("IL_"); sb.AppendFormat("{0:X4}", offset); } private static void PadForInstructionArgument(StringBuilder sb) { if (sb.Length < 22) sb.Append(' ', 22 - sb.Length); else sb.Append(' '); } public bool HasNextInstruction { get { return _currentOffset < _ilBytes.Length; } } public int CodeSize { get { return _ilBytes.Length; } } public string GetNextInstruction() { StringBuilder decodedInstruction = new StringBuilder(); AppendOffset(decodedInstruction, _currentOffset); decodedInstruction.Append(": "); again: ILOpcode opCode = (ILOpcode)ReadILByte(); if (opCode == ILOpcode.prefix1) { opCode = (ILOpcode)(0x100 + ReadILByte()); } // Quick and dirty way to get the opcode name is to convert the enum value to string. // We need some adjustments though. string opCodeString = opCode.ToString().Replace("_", "."); if (opCodeString.EndsWith(".")) opCodeString = opCodeString.Substring(0, opCodeString.Length - 1); decodedInstruction.Append(opCodeString); switch (opCode) { case ILOpcode.ldarg_s: case ILOpcode.ldarga_s: case ILOpcode.starg_s: case ILOpcode.ldloc_s: case ILOpcode.ldloca_s: case ILOpcode.stloc_s: case ILOpcode.ldc_i4_s: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILByte().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.unaligned: decodedInstruction.Append(' '); decodedInstruction.Append(ReadILByte().ToStringInvariant()); decodedInstruction.Append(' '); goto again; case ILOpcode.ldarg: case ILOpcode.ldarga: case ILOpcode.starg: case ILOpcode.ldloc: case ILOpcode.ldloca: case ILOpcode.stloc: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt16().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_i4: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt32().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_r4: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILFloat().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_i8: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt64().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_r8: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILDouble().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.jmp: case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.cpobj: case ILOpcode.ldobj: case ILOpcode.ldstr: case ILOpcode.newobj: case ILOpcode.castclass: case ILOpcode.isinst: case ILOpcode.unbox: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.stfld: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.stsfld: case ILOpcode.stobj: case ILOpcode.box: case ILOpcode.newarr: case ILOpcode.ldelema: case ILOpcode.ldelem: case ILOpcode.stelem: case ILOpcode.unbox_any: case ILOpcode.refanyval: case ILOpcode.mkrefany: case ILOpcode.ldtoken: case ILOpcode.ldftn: case ILOpcode.ldvirtftn: case ILOpcode.initobj: case ILOpcode.constrained: case ILOpcode.sizeof_: PadForInstructionArgument(decodedInstruction); AppendToken(decodedInstruction, ReadILToken()); return decodedInstruction.ToString(); case ILOpcode.br_s: case ILOpcode.leave_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: PadForInstructionArgument(decodedInstruction); AppendOffset(decodedInstruction, (sbyte)ReadILByte() + _currentOffset); return decodedInstruction.ToString(); case ILOpcode.br: case ILOpcode.leave: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: PadForInstructionArgument(decodedInstruction); AppendOffset(decodedInstruction, (int)ReadILUInt32() + _currentOffset); return decodedInstruction.ToString(); case ILOpcode.switch_: { decodedInstruction.Clear(); decodedInstruction.Append("switch ("); uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); for (uint i = 0; i < count; i++) { if (i != 0) decodedInstruction.Append(", "); int delta = (int)ReadILUInt32(); AppendOffset(decodedInstruction, jmpBase + delta); } decodedInstruction.Append(")"); return decodedInstruction.ToString(); } default: return decodedInstruction.ToString(); } } #endregion #region Helpers private class ILTypeNameFormatter : TypeNameFormatter { private ModuleDesc _thisModule; public ILTypeNameFormatter(ModuleDesc thisModule) { _thisModule = thisModule; } public void AppendNameWithValueClassPrefix(StringBuilder sb, TypeDesc type) { if (!type.IsSignatureVariable && type.IsDefType && !type.IsPrimitive && !type.IsObject && !type.IsString) { string prefix = type.IsValueType ? "valuetype " : "class "; sb.Append(prefix); AppendName(sb, type); } else { AppendName(sb, type); } } public override void AppendName(StringBuilder sb, PointerType type) { AppendNameWithValueClassPrefix(sb, type.ParameterType); sb.Append('*'); } public override void AppendName(StringBuilder sb, SignatureMethodVariable type) { sb.Append("!!"); sb.Append(type.Index.ToStringInvariant()); } public override void AppendName(StringBuilder sb, SignatureTypeVariable type) { sb.Append("!"); sb.Append(type.Index.ToStringInvariant()); } public override void AppendName(StringBuilder sb, GenericParameterDesc type) { string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!"; sb.Append(prefix); sb.Append(type.Name); } protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type) { AppendName(sb, type.GetTypeDefinition()); sb.Append('<'); for (int i = 0; i < type.Instantiation.Length; i++) { if (i > 0) sb.Append(", "); AppendNameWithValueClassPrefix(sb, type.Instantiation[i]); } sb.Append('>'); } public override void AppendName(StringBuilder sb, ByRefType type) { AppendNameWithValueClassPrefix(sb, type.ParameterType); sb.Append('&'); } public override void AppendName(StringBuilder sb, ArrayType type) { AppendNameWithValueClassPrefix(sb, type.ElementType); sb.Append('['); sb.Append(',', type.Rank - 1); sb.Append(']'); } protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) { switch (type.Category) { case TypeFlags.Void: sb.Append("void"); return; case TypeFlags.Boolean: sb.Append("bool"); return; case TypeFlags.Char: sb.Append("char"); return; case TypeFlags.SByte: sb.Append("int8"); return; case TypeFlags.Byte: sb.Append("uint8"); return; case TypeFlags.Int16: sb.Append("int16"); return; case TypeFlags.UInt16: sb.Append("uint16"); return; case TypeFlags.Int32: sb.Append("int32"); return; case TypeFlags.UInt32: sb.Append("uint32"); return; case TypeFlags.Int64: sb.Append("int64"); return; case TypeFlags.UInt64: sb.Append("uint64"); return; case TypeFlags.IntPtr: sb.Append("native int"); return; case TypeFlags.UIntPtr: sb.Append("native uint"); return; case TypeFlags.Single: sb.Append("float32"); return; case TypeFlags.Double: sb.Append("float64"); return; } if (type.IsString) { sb.Append("string"); return; } if (type.IsObject) { sb.Append("object"); return; } AppendNameForNamespaceTypeWithoutAliases(sb, type); } public void AppendNameForNamespaceTypeWithoutAliases(StringBuilder sb, DefType type) { ModuleDesc owningModule = (type as MetadataType)?.Module; if (owningModule != null && owningModule != _thisModule) { Debug.Assert(owningModule is IAssemblyDesc); string owningModuleName = ((IAssemblyDesc)owningModule).GetName().Name; sb.Append('['); sb.Append(owningModuleName); sb.Append(']'); } string ns = type.Namespace; if (ns.Length > 0) { sb.Append(ns); sb.Append('.'); } sb.Append(type.Name); } protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) { AppendName(sb, containingType); sb.Append('/'); sb.Append(nestedType.Name); } } #endregion } }
{ "task_name": "lcc" }
Passage 1: The Goose Steps Out Will Hay shared directorial credit with Basil Dearden following on from their previous collaboration, The Black Sheep of Whitehall. Art Director, Michael Relph described Dearden and Hay's input as directors 'Basil was very expert at directing comedy, and that is what he contributed when working with Will Hay. Hay was important as a star, and he could more or less dictate what he wanted to direct, but really he did not direct. Basil directed and supplied all the expertise that Hay probably lacked.' Barry Morse who played Kurt had a slightly different take on the directorial responsibilities. 'Basil Dearden was largely concerned with purely technical things, angles, lenses, lighting details. He didn't have a very active part, it seemed to me, in the actual performance directing. That was something which Will Hay had a certain amount to do with.'"The Goose Steps Out" is also noted as the film debut of a young Peter Ustinov. Passage 2: Rose Ann Scamardella Rose Ann Scamardella graduated from Marymount Manhattan College with a B.A. in sociology in 1968. After working for Gerald Freedman, a stockbroker, for "a couple of years" by her own account, she became the personnel director of an export company. By 1972, referred to in "The Village Voice" as "Roseann" Scamardella, she was working as what the paper identified only as a "television journalist". Passage 3: What Women Dream What Women Dream (German: Was Frauen träumen) is a 1933 German comedy crime film directed by Géza von Bolváry and starring Nora Gregor, Gustav Fröhlich and Otto Wallburg. In 1934 it was remade as an American film "One Exciting Adventure". The film's sets were designed by the art directors Emil Hasler and Willy Schiller. Passage 4: The Day Shall Dawn "The Day Shall Dawn" was very much a co-production between the two halves of what was then a geographically divided Pakistani state (now independent Pakistan and Bangladesh). The film was shot in Dhaka, East Pakistan (now Bangladesh) by the East Pakistan Film Development Corporation by a director from Lahore (in West Pakistan) and scripted in the Urdu language, which is native to the West. He selected Zahir Raihan as assistant director of the film. The film's music was provided by prominent Indian composer Timir Baran. Passage 5: Donald M. Ashton Donald M. Ashton (26 June 1919 – 25 August 2004) was an Academy Award-nominated and BAFTA-winning English art director most noted for his work on such films as "Billy Budd" (1962), "The Bridge on the River Kwai" (1957), "Oh! What a Lovely War" (1969) and "Young Winston" (1972). Passage 6: Sam Reed (musician) Working at the Uptown Theater in the late 1950s and early 1960s, he added jazz and rhythm & blues shows to what was at the time an R&B, blues and rock and roll venue. For some years, Reed was also musical director for Teddy Pendergrass, and in the early 1970s, he was the "horn contractor" for Gamble and Huff's Philadelphia International Records. Passage 7: Alba Mujica Alba Mujica (née Alba Mugica; 1916 in Carhué – 1983 in Buenos Aires) was an Argentina film and stage actress. She was the sister of actor and film director René Mugica. Her mother was the actress Emilia Rosales (Emilia Mugica). She was the mother of the actress Bárbara Mujica. Mujica attended school in La Plata. She was an actress in Argentine theater and cinema in the 1950s and 1960s. Her memoir "El tiempo entre los dientes" was published in 1967. Carhué's Italian Mutual Society Entertainment Hall is named in named "René Mugica and Mugica Alba" in recognition of the siblings. Passage 8: David Lauren David Lauren (born October 31, 1971) is the middle child and youngest son of clothing designer Ralph Lauren. His siblings are Dylan and Andrew Lauren. Passage 9: The Legendary Siblings The Legendary Siblings is a Taiwanese television series adapted from Gu Long's novel "Juedai Shuangjiao". The series was directed by Lee Kwok-lap and starred Jimmy Lin and Alec Su in the leading roles. It was first broadcast on TTV in Taiwan in 1999 and was followed by "The Legendary Siblings 2" in 2002. Passage 10: Men of Tomorrow Men of Tomorrow is a 1932 British drama film, directed by Zoltan Korda and Leontine Sagan, produced by Alexander Korda and written by Anthony Gibbs and Arthur Wimperis. It stars Maurice Braddell, Joan Gardner and Emlyn Williams and features Robert Donat's movie debut. Passage 11: Guardians of the Galaxy (film) Karen Gillan as Nebula: An adopted daughter of Thanos who was raised with Gamora as siblings and is a loyal lieutenant in the employ of Ronan and Thanos. About the character, Gillan said, ``She is the female villain of the film... She is very sadistic and evil, but I like to think for a very valid reason. ''She also added,`` I think she's a really interesting character. What I like to play around with is how jealous she is. She's Gamora's sister, and there's a lot of sibling rivalry. That's the most interesting aspect to me, because jealousy can consume you and turn you bitter, and ugly. And she's a total sadist, so that's fun too.'' Gillan researched the ancient Spartans, shaved off her hair, and trained for two months for the role. The character's makeup took approximately four and a half hours to be applied. Passage 12: Devil's Pass Director Renny Harlin spent time in Moscow researching the government archives. His own theory of what happened at the Dyatlov Pass incident is that a government experiment went wrong. The casting for the film was intentionally kept to unknowns. Shooting took place in northern Russia, and each scene was rehearsed extensively. Passage 13: Sibling Half - siblings are people who share one parent but not both. They may share the same mother but different fathers (in which case they are known as uterine siblings or maternal half - brothers / half - sisters), or they may have the same father but different mothers (in which case, they are known as agnate siblings or paternal half - brothers / half - sisters. In law, the term consanguine is used in place of agnate). They share only one parent instead of two as full siblings do and are on average 25% related. Passage 14: Miguel Piñera Miguel Piñera is the fifth son of José Piñera Carvallo and Magdalena Echenique Rozas. His siblings are Guadalupe, José, Sebastián, Pablo, and María Teresa. Passage 15: George William Weidler George William Weidler was one of six children born to the architect Alfred Weidler (1886–1966) and opera singer Margarete Therese Louisa (née Radon). The first four siblings (Waldtraud, Verena, Werther, and Wolfgang) were born in Germany. The eldest sibling, Waldtraud (later known as Sylvia) and the youngest sibling, Virginia, were both child film actresses. And one of his three brothers, Warner (born Werner Alfred Weidler), was a composer. Passage 16: Liliana Mayo Liliana Mayo is the founder and general director of Centro Ann Sullivan del Perú, an organization that serves people with developmental disabilities and their families. She is a frequent key speaker on parent and sibling training, supported employment opportunities for people with developmental disabilities, inclusion and distance education. She is a professor of special education at the Pontificia Universidad Católica del Perú and Universidad Peruana Cayetano Heredia, and adjunct faculty member of the Applied Behavioral Science Department at the University of Kansas. She received her B.S. degree in psychology from the Universidad Nacional Mayor de San Marcos, and her M.A. and Ph.D. degrees in Human Development and Family Life from the University of Kansas. Passage 17: Color Me Blood Red Color Me Blood Red is a 1965 splatter film written and directed by Herschell Gordon Lewis about a psychotic painter who murders civilians and uses their blood as red paint. It is the third part of what the director's fans have dubbed "The Blood Trilogy", including "Blood Feast" (1963) and "Two Thousand Maniacs!" (1964). Passage 18: I'm Feeling Lucky (book) I'm Feeling Lucky: The Confessions of Google Employee Number 59 is a 2011 book by Douglas Edwards, who was Google's first director of marketing and brand management. The book tells his story of what it was to be on the inside during the rise of one of the most powerful internet companies from its start-up beginnings. Passage 19: Adolescence During childhood, siblings are a source of conflict and frustration as well as a support system. Adolescence may affect this relationship differently, depending on sibling gender. In same-sex sibling pairs, intimacy increases during early adolescence, then remains stable. Mixed-sex siblings pairs act differently; siblings drift apart during early adolescent years, but experience an increase in intimacy starting at middle adolescence. Sibling interactions are children's first relational experiences, the ones that shape their social and self-understanding for life. Sustaining positive sibling relations can assist adolescents in a number of ways. Siblings are able to act as peers, and may increase one another's sociability and feelings of self-worth. Older siblings can give guidance to younger siblings, although the impact of this can be either positive or negative depending on the activity of the older sibling. Passage 20: Yamata Yamata is a 1919 Hungarian silent drama film directed by Alexander Korda and starring Emil Fenyvessy, Ila Lóth and Gábor Rajnay. The film was made for the state-owned Hungarian film industry during the Hungarian Soviet Republic, and concerns a black slave's revolt against his master. The film's apparent political leftism, along with that of "Ave Caesar!" (1919), led to Korda's arrest once the Soviet Republic collapsed and he fled Hungary in 1919 during the White Terror. Question: Who is the sibling of Yamata's director? Answer: Zoltan Korda
{ "task_name": "MuSiQue" }
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import mock import grpc from grpc.experimental import aio from collections.abc import Iterable import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from requests import Response from requests import Request, PreparedRequest from requests.sessions import Session from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.node_types import NodeTypesClient from google.cloud.compute_v1.services.node_types import pagers from google.cloud.compute_v1.services.node_types import transports from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth def client_cert_source_callback(): return b"cert bytes", b"key bytes" # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): return ( "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT ) def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" assert NodeTypesClient._get_default_mtls_endpoint(None) is None assert NodeTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint assert ( NodeTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint ) assert ( NodeTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint ) assert ( NodeTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint ) assert NodeTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi @pytest.mark.parametrize("client_class,transport_name", [(NodeTypesClient, "rest"),]) def test_node_types_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( "compute.googleapis.com{}".format(":443") if transport_name in ["grpc", "grpc_asyncio"] else "https://{}".format("compute.googleapis.com") ) @pytest.mark.parametrize( "transport_class,transport_name", [(transports.NodeTypesRestTransport, "rest"),] ) def test_node_types_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() @pytest.mark.parametrize("client_class,transport_name", [(NodeTypesClient, "rest"),]) def test_node_types_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds client = client_class.from_service_account_file( "dummy/file/path.json", transport=transport_name ) assert client.transport._credentials == creds assert isinstance(client, client_class) client = client_class.from_service_account_json( "dummy/file/path.json", transport=transport_name ) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( "compute.googleapis.com{}".format(":443") if transport_name in ["grpc", "grpc_asyncio"] else "https://{}".format("compute.googleapis.com") ) def test_node_types_client_get_transport_class(): transport = NodeTypesClient.get_transport_class() available_transports = [ transports.NodeTypesRestTransport, ] assert transport in available_transports transport = NodeTypesClient.get_transport_class("rest") assert transport == transports.NodeTypesRestTransport @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(NodeTypesClient, transports.NodeTypesRestTransport, "rest"),], ) @mock.patch.object( NodeTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NodeTypesClient) ) def test_node_types_client_client_options( client_class, transport_class, transport_name ): # Check that if channel is provided we won't create a new one. with mock.patch.object(NodeTypesClient, "get_transport_class") as gtc: transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. with mock.patch.object(NodeTypesClient, "get_transport_class") as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,use_client_cert_env", [ (NodeTypesClient, transports.NodeTypesRestTransport, "rest", "true"), (NodeTypesClient, transports.NodeTypesRestTransport, "rest", "false"), ], ) @mock.patch.object( NodeTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NodeTypesClient) ) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) def test_node_types_client_mtls_env_auto( client_class, transport_class, transport_name, use_client_cert_env ): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None expected_host = client.DEFAULT_ENDPOINT else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=client_cert_source_callback, ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT expected_client_cert_source = client_cert_source_callback patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize("client_class", [NodeTypesClient]) @mock.patch.object( NodeTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NodeTypesClient) ) def test_node_types_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): ( api_endpoint, cert_source, ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(NodeTypesClient, transports.NodeTypesRestTransport, "rest"),], ) def test_node_types_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,grpc_helpers", [(NodeTypesClient, transports.NodeTypesRestTransport, "rest", None),], ) def test_node_types_client_client_options_credentials_file( client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "request_type", [compute.AggregatedListNodeTypesRequest, dict,] ) def test_aggregated_list_rest(request_type): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeTypeAggregatedList( id="id_value", kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", unreachables=["unreachables_value"], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeAggregatedList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.aggregated_list(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.AggregatedListPager) assert response.id == "id_value" assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" assert response.unreachables == ["unreachables_value"] def test_aggregated_list_rest_required_fields( request_type=compute.AggregatedListNodeTypesRequest, ): transport_class = transports.NodeTypesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).aggregated_list._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).aggregated_list._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( "filter", "include_all_scopes", "max_results", "order_by", "page_token", "return_partial_success", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.NodeTypeAggregatedList() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeAggregatedList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.aggregated_list(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_aggregated_list_rest_unset_required_fields(): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.aggregated_list._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( "filter", "includeAllScopes", "maxResults", "orderBy", "pageToken", "returnPartialSuccess", ) ) & set(("project",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_aggregated_list_rest_interceptors(null_interceptor): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.NodeTypesRestInterceptor(), ) client = NodeTypesClient(transport=transport) with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( transports.NodeTypesRestInterceptor, "post_aggregated_list" ) as post, mock.patch.object( transports.NodeTypesRestInterceptor, "pre_aggregated_list" ) as pre: pre.assert_not_called() post.assert_not_called() transcode.return_value = { "method": "post", "uri": "my_uri", "body": None, "query_params": {}, } req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = compute.NodeTypeAggregatedList.to_json( compute.NodeTypeAggregatedList() ) request = compute.AggregatedListNodeTypesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = compute.NodeTypeAggregatedList client.aggregated_list( request, metadata=[("key", "val"), ("cephalopod", "squid"),] ) pre.assert_called_once() post.assert_called_once() def test_aggregated_list_rest_bad_request( transport: str = "rest", request_type=compute.AggregatedListNodeTypesRequest ): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.aggregated_list(request) def test_aggregated_list_rest_flattened(): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeTypeAggregatedList() # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1"} # get truthy value for each flattened field mock_args = dict(project="project_value",) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeAggregatedList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.aggregated_list(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "%s/compute/v1/projects/{project}/aggregated/nodeTypes" % client.transport._host, args[1], ) def test_aggregated_list_rest_flattened_error(transport: str = "rest"): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.aggregated_list( compute.AggregatedListNodeTypesRequest(), project="project_value", ) def test_aggregated_list_rest_pager(transport: str = "rest"): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( compute.NodeTypeAggregatedList( items={ "a": compute.NodeTypesScopedList(), "b": compute.NodeTypesScopedList(), "c": compute.NodeTypesScopedList(), }, next_page_token="abc", ), compute.NodeTypeAggregatedList(items={}, next_page_token="def",), compute.NodeTypeAggregatedList( items={"g": compute.NodeTypesScopedList(),}, next_page_token="ghi", ), compute.NodeTypeAggregatedList( items={ "h": compute.NodeTypesScopedList(), "i": compute.NodeTypesScopedList(), }, ), ) # Two responses for two calls response = response + response # Wrap the values into proper Response objs response = tuple(compute.NodeTypeAggregatedList.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values sample_request = {"project": "sample1"} pager = client.aggregated_list(request=sample_request) assert isinstance(pager.get("a"), compute.NodeTypesScopedList) assert pager.get("h") is None results = list(pager) assert len(results) == 6 assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) assert tuple(type(t) for t in result) == (str, compute.NodeTypesScopedList) assert pager.get("a") is None assert isinstance(pager.get("h"), compute.NodeTypesScopedList) pages = list(client.aggregated_list(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.parametrize("request_type", [compute.GetNodeTypeRequest, dict,]) def test_get_rest(request_type): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2", "node_type": "sample3"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeType( cpu_platform="cpu_platform_value", creation_timestamp="creation_timestamp_value", description="description_value", guest_cpus=1090, id=205, kind="kind_value", local_ssd_gb=1244, memory_mb=967, name="name_value", self_link="self_link_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeType.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.NodeType) assert response.cpu_platform == "cpu_platform_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.guest_cpus == 1090 assert response.id == 205 assert response.kind == "kind_value" assert response.local_ssd_gb == 1244 assert response.memory_mb == 967 assert response.name == "name_value" assert response.self_link == "self_link_value" assert response.zone == "zone_value" def test_get_rest_required_fields(request_type=compute.GetNodeTypeRequest): transport_class = transports.NodeTypesRestTransport request_init = {} request_init["node_type"] = "" request_init["project"] = "" request_init["zone"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["nodeType"] = "node_type_value" jsonified_request["project"] = "project_value" jsonified_request["zone"] = "zone_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "nodeType" in jsonified_request assert jsonified_request["nodeType"] == "node_type_value" assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "zone" in jsonified_request assert jsonified_request["zone"] == "zone_value" client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.NodeType() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeType.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_rest_unset_required_fields(): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("nodeType", "project", "zone",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_rest_interceptors(null_interceptor): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.NodeTypesRestInterceptor(), ) client = NodeTypesClient(transport=transport) with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( transports.NodeTypesRestInterceptor, "post_get" ) as post, mock.patch.object( transports.NodeTypesRestInterceptor, "pre_get" ) as pre: pre.assert_not_called() post.assert_not_called() transcode.return_value = { "method": "post", "uri": "my_uri", "body": None, "query_params": {}, } req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = compute.NodeType.to_json(compute.NodeType()) request = compute.GetNodeTypeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = compute.NodeType client.get(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() def test_get_rest_bad_request( transport: str = "rest", request_type=compute.GetNodeTypeRequest ): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2", "node_type": "sample3"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.get(request) def test_get_rest_flattened(): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeType() # get arguments that satisfy an http rule for this method sample_request = { "project": "sample1", "zone": "sample2", "node_type": "sample3", } # get truthy value for each flattened field mock_args = dict( project="project_value", zone="zone_value", node_type="node_type_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeType.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.get(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "%s/compute/v1/projects/{project}/zones/{zone}/nodeTypes/{node_type}" % client.transport._host, args[1], ) def test_get_rest_flattened_error(transport: str = "rest"): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get( compute.GetNodeTypeRequest(), project="project_value", zone="zone_value", node_type="node_type_value", ) def test_get_rest_error(): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.ListNodeTypesRequest, dict,]) def test_list_rest(request_type): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeTypeList( id="id_value", kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" def test_list_rest_required_fields(request_type=compute.ListNodeTypesRequest): transport_class = transports.NodeTypesRestTransport request_init = {} request_init["project"] = "" request_init["zone"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["zone"] = "zone_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ("filter", "max_results", "order_by", "page_token", "return_partial_success",) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "zone" in jsonified_request assert jsonified_request["zone"] == "zone_value" client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.NodeTypeList() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_rest_unset_required_fields(): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.list._get_unset_required_fields({}) assert set(unset_fields) == ( set(("filter", "maxResults", "orderBy", "pageToken", "returnPartialSuccess",)) & set(("project", "zone",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_rest_interceptors(null_interceptor): transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.NodeTypesRestInterceptor(), ) client = NodeTypesClient(transport=transport) with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( transports.NodeTypesRestInterceptor, "post_list" ) as post, mock.patch.object( transports.NodeTypesRestInterceptor, "pre_list" ) as pre: pre.assert_not_called() post.assert_not_called() transcode.return_value = { "method": "post", "uri": "my_uri", "body": None, "query_params": {}, } req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = compute.NodeTypeList.to_json(compute.NodeTypeList()) request = compute.ListNodeTypesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = compute.NodeTypeList client.list(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() def test_list_rest_bad_request( transport: str = "rest", request_type=compute.ListNodeTypesRequest ): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.list(request) def test_list_rest_flattened(): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.NodeTypeList() # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "zone": "sample2"} # get truthy value for each flattened field mock_args = dict(project="project_value", zone="zone_value",) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.NodeTypeList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.list(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "%s/compute/v1/projects/{project}/zones/{zone}/nodeTypes" % client.transport._host, args[1], ) def test_list_rest_flattened_error(transport: str = "rest"): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list( compute.ListNodeTypesRequest(), project="project_value", zone="zone_value", ) def test_list_rest_pager(transport: str = "rest"): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( compute.NodeTypeList( items=[compute.NodeType(), compute.NodeType(), compute.NodeType(),], next_page_token="abc", ), compute.NodeTypeList(items=[], next_page_token="def",), compute.NodeTypeList(items=[compute.NodeType(),], next_page_token="ghi",), compute.NodeTypeList(items=[compute.NodeType(), compute.NodeType(),],), ) # Two responses for two calls response = response + response # Wrap the values into proper Response objs response = tuple(compute.NodeTypeList.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values sample_request = {"project": "sample1", "zone": "sample2"} pager = client.list(request=sample_request) results = list(pager) assert len(results) == 6 assert all(isinstance(i, compute.NodeType) for i in results) pages = list(client.list(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( client_options={"credentials_file": "credentials.json"}, transport=transport, ) # It is an error to provide an api_key and a transport instance. transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): client = NodeTypesClient(client_options=options, transport=transport,) # It is an error to provide an api_key and a credential. options = mock.Mock() options.api_key = "api_key" with pytest.raises(ValueError): client = NodeTypesClient( client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NodeTypesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) client = NodeTypesClient(transport=transport) assert client.transport is transport @pytest.mark.parametrize("transport_class", [transports.NodeTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_node_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NodeTypesTransport( credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) def test_node_types_base_transport(): # Instantiate the base transport. with mock.patch( "google.cloud.compute_v1.services.node_types.transports.NodeTypesTransport.__init__" ) as Transport: Transport.return_value = None transport = transports.NodeTypesTransport( credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "aggregated_list", "get", "list", ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) with pytest.raises(NotImplementedError): transport.close() def test_node_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.node_types.transports.NodeTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id="octopus", ) def test_node_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.node_types.transports.NodeTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTypesTransport() adc.assert_called_once() def test_node_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) NodeTypesClient() adc.assert_called_once_with( scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id=None, ) def test_node_types_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: transports.NodeTypesRestTransport( credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) @pytest.mark.parametrize("transport_name", ["rest",]) def test_node_types_host_no_port(transport_name): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), transport=transport_name, ) assert client.transport._host == ( "compute.googleapis.com:443" if transport_name in ["grpc", "grpc_asyncio"] else "https://compute.googleapis.com" ) @pytest.mark.parametrize("transport_name", ["rest",]) def test_node_types_host_with_port(transport_name): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), transport=transport_name, ) assert client.transport._host == ( "compute.googleapis.com:8000" if transport_name in ["grpc", "grpc_asyncio"] else "https://compute.googleapis.com:8000" ) def test_common_billing_account_path(): billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) actual = NodeTypesClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): expected = { "billing_account": "clam", } path = NodeTypesClient.common_billing_account_path(**expected) # Check that the path construction is reversible. actual = NodeTypesClient.parse_common_billing_account_path(path) assert expected == actual def test_common_folder_path(): folder = "whelk" expected = "folders/{folder}".format(folder=folder,) actual = NodeTypesClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): expected = { "folder": "octopus", } path = NodeTypesClient.common_folder_path(**expected) # Check that the path construction is reversible. actual = NodeTypesClient.parse_common_folder_path(path) assert expected == actual def test_common_organization_path(): organization = "oyster" expected = "organizations/{organization}".format(organization=organization,) actual = NodeTypesClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): expected = { "organization": "nudibranch", } path = NodeTypesClient.common_organization_path(**expected) # Check that the path construction is reversible. actual = NodeTypesClient.parse_common_organization_path(path) assert expected == actual def test_common_project_path(): project = "cuttlefish" expected = "projects/{project}".format(project=project,) actual = NodeTypesClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): expected = { "project": "mussel", } path = NodeTypesClient.common_project_path(**expected) # Check that the path construction is reversible. actual = NodeTypesClient.parse_common_project_path(path) assert expected == actual def test_common_location_path(): project = "winkle" location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) actual = NodeTypesClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): expected = { "project": "scallop", "location": "abalone", } path = NodeTypesClient.common_location_path(**expected) # Check that the path construction is reversible. actual = NodeTypesClient.parse_common_location_path(path) assert expected == actual def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( transports.NodeTypesTransport, "_prep_wrapped_messages" ) as prep: client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object( transports.NodeTypesTransport, "_prep_wrapped_messages" ) as prep: transport_class = NodeTypesClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) def test_transport_close(): transports = { "rest": "_session", } for transport, close_name in transports.items(): client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) with mock.patch.object( type(getattr(client.transport, close_name)), "close" ) as close: with client: close.assert_not_called() close.assert_called_once() def test_client_ctx(): transports = [ "rest", ] for transport in transports: client = NodeTypesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: close.assert_not_called() with client: pass close.assert_called() @pytest.mark.parametrize( "client_class,transport_class", [(NodeTypesClient, transports.NodeTypesRestTransport),], ) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True ) as get_api_key_credentials: mock_cred = mock.Mock() get_api_key_credentials.return_value = mock_cred options = client_options.ClientOptions() options.api_key = "api_key" with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, )
{ "task_name": "lcc" }
Document: SEATTLE, WA - Two women were found dead inside a University District apartment near the University of Washington Tuesday morning, according to Seattle police. It's unclear how the women died, but Seattle detectives have determined there are no suspects at-large. According to Seattle police, the building manager went to a unit in the Malloy Apartments near the intersection of 15th Avenue Northeast and Northeast 43rd Street around 9:30 a.m. for a welfare check. That's when he discovered the victims. According to Seattle fire 911 records, medics responded to 4423 15th Avenue Northeast around 9:30 a.m. The Malloy Apartments is a 123-unit building made up of mostly studio and small one-bedroom units. The incident was originally reported as a stabbing. UW police sent out a campus-wide alert warning students to avoid the area just before 9:30 a.m. "Homicide investigators are on scene and actively working to determine the circumstances of this case, and whether there are any outstanding individuals involved in this incident," Seattle police wrote in a bulletin Tuesday morning. The King County Medical Examiner will determine the cause and manner of death. There hasn't been a double-homicide in the University District in at least 10 years. There have only been five homicides in the University District since 2008, according to Seattle police crime statistics. There have been 18 homicides in 2018 in Seattle. The last occurred on Saturday in the International District. A 56-year-old man died after he was apparently stabbed in the leg, according to Seattle police. Officers responding to stabbing at apartment in 4300 block of 15th Ave Ne. One woman with significant injuries. More details as this develops. — Seattle Police Dept. (@SeattlePD) September 4, 2018 Photo via Google Maps ||||| Two women were found dead in an apartment building across the street from the University of Washington campus on Tuesday, police said. The Seattle Police Department said the two women were in their 20s and “there are no outstanding suspects,” indicating the deaths may have been a murder-suicide. The department said in a written statement that officers went to the apartment at about 9:30 a.m. Tuesday after building managers found a seriously injured woman inside. Officers entered and found the two women dead and one appeared to have been stabbed. BLOOD DRIPPING FROM CEILING UNCOVERS APPARENT MURDER-SUICIDE, POLICE SAY The King County Medical Examiner will determine the women's cause of death and confirm their identities. Malloy Apartments, the building where the women were found, is a popular residential location for University of Washington students, Q13 Fox reported. The news of the deaths rattled some neighbors. “That’s just really terrifying to hear it’s close to where I am,” Anna Cinamon told Q13 Fox. “It makes you stop and think, you know. Are you really as safe as you think you are?” Richard Johnson, a neighbor, said. VIDEO OF FLORIDA MOM DUNKING 3-YEAR-OLD’S HEAD IN TOILET PROMPTS POLICE INVESTIGATION “I’m absolutely going to make sure that the doors are locked and that everything like that is in order and use the buddy system,” he continued. “It’s really terrifying for sure.” The Associated Press contributed to this report. ||||| “The room was locked from the inside when the building manager tried to gain entry, apparently adding substance to the theory there was nobody else involved.” Kornkamol Leenawarat left from Thailand back to Seattle, Washington on August 21. Just two weeks later she has been found dead in her apartment along with the body of her roommate Thiti-orn Chotchuangsap. The only daughter and youngest child in her family, Kornkamol returned home early last month to celebrate Mother’s Day on August 12 with her father and older brothers; her mother had already passed away. Seattle police are investigating the murders of both Washington University post-graduate students. Reports of the killings detailed how the victims’ bodies were riddled with knife wounds, causing alarm in Seattle that such a vicious act could occur in the quiet residential area close to the university and in a city regarded as one of the safest in the United States. Kornkamol was studying law in Seattle, having graduated with a bachelor’s degree from Thammasat University and attained a master’s degree, also in law, from a university in Boston, Massachusetts. Her family lives in Pathum Thani province, where they are well known, due to some of them being local politicians. They say Kornkamol’s ultimate goal was to one day become a judge. The only information to have emerged so far about Thiti-orn is that she was from Samut Sakhon province. Deputy immigration police commissioner Itthipon Itthisarnronnachai said yesterday he had been notified that both bodies had been discovered on Tuesday bearing multiple stab wounds. He declined to speculate on details surrounding the deaths, in particular on speculation in US media reports that this was a murder or murder-suicide. The murder-suicide theory was raised following a report that the apartment was locked from the inside when a building manager went to check it at the request of Kornkamon’s family, made through their relative in the US. Kornkamol contacted her family almost daily, so they were immediately concerned after they failed to reach her and university administration officers told them she had been absent from class for many days. Ittipon confirmed the report that the room was locked from the inside when the building manager tried to gain entry, apparently adding substance to the theory there was nobody else involved. Moreover US police have declared that they are not seeking any suspects. Speaking at the same press conference, Pol Lt General Suthipong Wongpin, immigration police commissioner, said immigration records showed that Kornkamol had left Thailand on August 21 and Thiti-orn on August 27. Immigration police will liaise with relevant authorities to help the families of both women travel to the US. An elder brother of Kornkamol, Weerasak Leenavarat, said that his family is in deep mourning for the loss of their friendly and lively daughter and sister. SOURCE: The Nation . ||||| The only daughter and youngest child in her family, Kornkamol returned home early last month to celebrate Mother’s Day on August 12 with her father and older brothers; her mother had already passed away. Seattle police are investigating the murders of both Washington University post-graduate students. Reports of the killings detailed how the victims’ bodies were riddled with knife wounds, causing alarm in Seattle that such a vicious act could occur in the quiet residential area close to the university and in a city regarded as one of the safest in the United States. Kornkamol was studying law in Seattle, having graduated with a bachelor’s degree from Thammasat University and attained a master’s degree, also in law, from a university in Boston, Massachusetts. Her family lives in Pathum Thani province, where they are well known, due to some of them being local politicians. They say Kornkamol’s ultimate goal was to one day become a judge. The only information to have emerged so far about Thiti-orn is that she was from Samut Sakhon province. Deputy immigration police commissioner Itthipon Itthisarnronnachai said yesterday he had been notified that both bodies had been discovered on Tuesday bearing multiple stab wounds. He declined to speculate on details surrounding the deaths, in particular on speculation in US media reports that this was a murder or murder-suicide. The murder-suicide theory was raised following a report that the apartment was locked from the inside when a building manager went to check it at the request of Kornkamon’s family, made through their relative in the US. Kornkamol contacted her family almost daily, so they were immediately concerned after they failed to reach her and university administration officers told them she had been absent from class for many days. Ittipon confirmed the report that the room was locked from the inside when the building manager tried to gain entry, apparently adding substance to the theory there was nobody else involved. Moreover US police have declared that they are not seeking any suspects. Speaking at the same press conference, Pol Lt General Suthipong Wongpin, immigration police commissioner, said immigration records showed that Kornkamol had left Thailand on August 21 and Thiti-orn on August 27. Immigration police will liaise with relevant authorities to help the families of both women travel to the US. An elder brother of Kornkamol, Weerasak Leenavarat, said that his family is in deep mourning for the loss of their friendly and lively daughter and sister. It was especially traumatic, he said, for their father, whose health was already poor. The rest of the family is now staying close to take special care of him at this time. Weerasak posted a series of photos on his Facebook page of the day Kornkamol flew to the US. The images show everybody smiling as they see off a beaming Kornkamol at Suvarnabhumi Airport. Weerasak called Kornkamol “our little sister who was always lively, friendly and brave”. A relative wrote that the last words Kornkamol told her were: “Don’t be so sad. I will only go to the US for a short period. I will come back very soon.” Summary: – Two women in their 20s were found dead in an apartment across the street from the University of Washington campus in Seattle on Tuesday, Fox News reports. Police say building managers found a seriously wounded woman inside the apartment Tuesday morning, and responding officers arrived to find both women dead. The incident was originally reported as a stabbing, Patch reports, but their causes of death have not yet been officially determined. The medical examiner has also not yet confirmed their identities, but the Bangkok Post IDs them as two close friends from Thailand. Seattle police say there are no outstanding suspects, which could indicate a murder-suicide; according to the Thaiger, there are also reports the apartment was locked from the inside when the women were found. Per the Post, the women are Kornkamol Leenavarat and Thiti-orn Chotchuangsap. According to her older brother, Leenavarat, 25, had just flown to the US two weeks prior to get her master's degree in law; he says Chotchuangsap was her roommate. Immigration records reportedly show that she, too, had only recently left Thailand. A local official says Leenavarat had called her family every day since leaving for the US, and when they didn't hear from her Saturday, they asked a relative in Seattle to check on her. The relative reportedly could not get in touch with her and ultimately asked the building manager to do a welfare check after the family also learned she had been absent from class. The Nation notes that Leenavarat's family is well-known in their Thai province due to some members being local politicians.
{ "task_name": "multi_news" }
Passage 1: Stratego Stratego is a strategy board game for two players on a board of 10×10 squares. Each player controls 40 pieces representing individual officer ranks in an army. The pieces have Napoleonic insignia. The objective of the game is to find and capture the opponent's "Flag", or to capture so many enemy pieces that the opponent cannot make any further moves. "Stratego" has simple enough rules for young children to play, but a depth of strategy that is also appealing to adults. The game is a slightly modified copy of an early 20th century French game named "L'Attaque". It has been in production in Europe since World War II and the United States since 1961. There are now 2- and 4-handed versions, versions with 10, 30 or 40 pieces per player, and boards with smaller sizes (number of spaces). There are also variant pieces and different rulesets. Passage 2: Luzhanqi Luzhanqi () (lit. “Land Battle Chess”) is a two-player Chinese board game . There is also a version for four players. It bears many similarities to Dou Shou Qi, Game of the Generals and the Western board game Stratego. It is a non-perfect abstract strategy game of partial information, since each player has only limited knowledge concerning the disposition of the opposing pieces. Because of the Chinese nature of the game, terms used within the game may vary in translation. Passage 3: Buga-shadara Buga-shadara, also known as Bouge Shodre, is a two-player abstract strategy board game from Tuva, a republic in Siberia, Russia. It is a hunt game where one player plays the deers (which is "buga" in the Tuva language). There are two deers usually represented as the black pieces. The boars are also referred black in the referenced article "Buga-shadara a folk game from Tuva". The other player has 24 white pieces with dogs associated to them. The board consist of an Alquerque board flanked on two of its opposite sides by a square patterned board (referred to as "side-houses" in the referenced article). Because the board is in part an Alquerque board, this makes Buga-shadara a tiger hunt game (or tiger game). What makes Buga-shadara unique among tiger games are the expansion boards on the two opposite sides of the Alquerque board. They are square, whereas most are triangle-like. The word "shadara" resembles the word "shahdara". The "shah" part "is a title given to the emperors/kings and lords of Iran (historically also known as Persia).". There is a place called Shahdara Bagh in Lahore, Punjab, Pakistan, and it's thought that the word "Shahdara can be translated as "the way of kings". Shah translates as "king" and dara translates as the way of kings." The referenced article associates the boars (the two black pieces) as kings. Perhaps the boars or deers are kings, and have to find a way or have a way with the white pieces or dogs. Passage 4: List of Wii games using WiiConnect24 This is a list of games on the Wii video game console that use WiiConnect24. WiiConnect24 games are distinguished from Wii Wi-Fi Connection games in that WiiConnect24 support only allows for passive connection between players, such as the sharing of credits in "" or "Metroid Prime Trilogy". Some games support both active connectivity with the Nintendo Wi-Fi Connection (requiring an independent 12-digit Friend Code), as well as passive connectivity with WiiConnect24 (only needing the Wii's own 16-digit Friend Code), such as "Mario Kart Wii". Passage 5: Havannah Havannah is a two-player abstract strategy board game invented by Christian Freeling. It belongs to the family of games commonly called connection games; its relatives include Hex and TwixT. Havannah has "a sophisticated and varied strategy" and is best played on a base-10 hexagonal board, ten hex cells to a side. Passage 6: Onyx (game) Onyx is a two-player abstract strategy board game invented by Larry Back in 1995. The game features a rule for performing captures, making Onyx unique among connection games. Passage 7: Selfo Selfo is a class of abstract strategy board games subscribed to the category of connection games. Its name derives from the phenomenon of self-organization (increase in a system's organization without external guidance), since during the game the sets of pieces might flow in a coordinated way as they step on the board. Despite its very simple definition (“group your set of pieces by moving in turns to adjacent cells”) complex self-organization processes take place during the game under concrete circumstances (a balanced distribution of pieces and players with a similar level of expertise), and is the result of abrupt and deep changes in the tactics. The particular values given to the traditional parameters that define a game (i.e., board tiling, size and initial position, or number of pieces and players) are not so relevant, and many variants have been found to meet the conditions for self-organization. The "Selfo" class of connection games is defined, instead, by the interrelations among parameters in order to favor self-organization. Subclasses of Selfo derive upon the move length (number of movements of a piece in a single turn to adjacent empty cells). In a generic "Selfo"-"n" game, a player can move one piece from 0 (passing on the turn) to "n" consecutive steps. Passage 8: Connection game A connection game is a type of abstract strategy game in which players attempt to complete a specific type of connection with their pieces. This could involve forming a path between two or more goals, completing a closed loop, or connecting all of one's pieces so they are adjacent to each other. Connection games typically have simple rules, but complex strategies. They have minimal components and may be played as board games, computer games, or even paper and pencil games. Passage 9: TAMSK TAMSK is the second board game in the "GIPF" Project of six abstract strategy games, and was published in 1998. Players move sand hourglass timers and drop plastic rings around spaces on a hexagonal board in an attempt to limit their opponent's moves. Each player starts the game with 32 rings, and the player with the fewest remaining rings at the end of the game is the winner. The game is unique among the "GIPF" Project games in having time as a central game component, and the manner in which time is used is possibly unique among board games in general. Passage 10: Stratego: Legends Stratego: Legends is a strategy board game created and released by Avalon Hill in 1999, with rules similar to "Stratego". Set in a mythical world called "The Shattered Lands", it pits the forces of good (represented by beige-back pieces) against the forces of evil (represented by gray-back pieces). It plays similar to the original "Stratego" game, and also somewhat similar to chess. The game was discontinued by Avalon Hill in 2004. Question: Which board game features a rule for performing captures, making it unique among connection games, Stratego or Onyx? Answer: Onyx
{ "task_name": "hotpotqa" }
Document: BOSTON (AP) — A federal jury has awarded $18.4 million in damages to a man who said in a lawsuit that two doctors failed to test him for HIV, which allowed the virus to progress to AIDS. The Boston Globe reports the jury ruled Monday in favor of 48-year-old Sean Stentiford in his medical malpractice lawsuit against internist Stephen Southard and neurologist Kinan Hreib. Stentiford said he consented to an HIV test in 2007 because he was experiencing facial paralysis. The suit says Hreib canceled the test because he felt Stentiford had no risk of HIV. Stentiford's lawyer says his client should have been tested because he is gay and was exposed to bodily fluids while working as a paramedic. Lawyers for the doctors did not immediately respond to requests for comment. ___ Information from: The Boston Globe, http://www.bostonglobe.com ||||| A federal jury in Boston on Monday awarded $18.4 million in damages to a man who alleged that two of his former physicians failed to test him for HIV despite risk factors that made him more vulnerable to contracting the disease. Sean Stentiford, 48, was more susceptible to developing the virus that causes AIDS because he is gay and earlier in his life worked as a paramedic, a job that regularly exposed him to bodily fluids, his lawyer, David P. Angueira, said Tuesday. But even though he consented to an HIV test in 2007, his doctors never performed one. About three years later, another doctor recommended the test, which came back positive, Angueira said. By then, the disease progressed to AIDS, causing Stentiford brain damage and ending his career as a lawyer. Advertisement “He had a brilliant future in front of him. They literally cut the legs out from under him,” Angueira said. “He lost his job. He lost his career. He lost his life.” Get Metro Headlines in your inbox: The 10 top local news stories from metro Boston and around New England delivered daily. Sign Up Thank you for signing up! Sign up for more newsletters here After an eight-day trial in US District Court, the jury found that two doctors, internist Stephen E. Southard and neurologist Kinan K. Hreib, were negligent in caring for Stentiford and caused him injury, court records show. The panel found that a third doctor, Daniel P. McQuillen, an infectious disease specialist, was also negligent, but his actions didn’t cause Stentiford harm, court papers show. During the medical malpractice trial, jurors were shown the consent form for HIV testing that Stentiford signed in May 2007 in the presence of his sister as he underwent a battery of tests at Lahey Hospital & Medical Center in Burlington because he was experiencing facial paralysis, Angueira said. Stentiford agreed to the testing, his lawsuit said, after a resident told him his symptoms were “highly suggestive of HIV infection.” Advertisement Hreib disagreed, according to the lawsuit. He noted in Stentiford’s medical record that there was “no risk of HIV,” though testing would be considered. Hreib canceled the test but never told Stentiford, according to Angueira. But when Stentiford visited the office of Southard, his primary care doctor, in June 2007, he was told his tests “looked good,” according to the lawsuit. Stentiford believed that assessment included HIV testing because he had signed the consent form. About three years later, as Stentiford’s condition worsened, Angueira said, his client learned he was not tested for HIV in 2007, and that he did in fact have the virus. By that time, Stentiford was struggling with brain damage and cognitive impairment. Since 2006, the Centers for Disease Control and Prevention have recommended that all patients between the ages of 13 and 64 be screened for HIV at least once, according to the agency’s website. For sexually active gay and bisexual men and other men who have sex with men, the agency recommends HIV testing every year, the website says. Advertisement As early as November 2006, Stentiford’s medical records at Lahey noted that he was gay; a licensed social worker wrote a note describing Stentiford as a “ ‘somewhat closeted’ gay man.” That note was available to other Lahey physicians who treated Stentiford, according to Angueira. In a statement, a Lahey spokesman said the hospital doesn’t agree with the “presentation of the facts” and plans to appeal the jury’s decision. “Quality care is our top priority and the health care providers of Lahey Hospital & Medical Center have an unwavering commitment to delivering the best care to every patient, every day,” said the spokesman, Chris Murphy. Southard and Hreib are no longer associated with Lahey, though McQuillen remains on staff, Murphy said. Lawyers for the doctors didn’t respond Tuesday to requests for comment. Stentiford now lives in the Bronx and no longer suffers from AIDS-related symptoms thanks to medication he takes to control his illness, Angueira said. He said Stentiford was solemn when the jury revealed its decision. “He was numb,” Angueira said. “I think it was overwhelming.” Follow her on Twitter @lauracrimaldi Laura Crimaldi can be reached at [email protected] Summary: – A federal jury has awarded $18.4 million in damages to a man who said in a lawsuit that two doctors failed to test him for HIV, which allowed the virus to progress to AIDS. The Boston Globe reports the jury ruled Monday in favor of 48-year-old Sean Stentiford in his medical malpractice lawsuit against internist Stephen Southard and neurologist Kinan Hreib. Stentiford said he consented to an HIV test in 2007 because he was experiencing facial paralysis. Per the AP, the suit says Hreib canceled the test because he felt Stentiford had no risk of HIV. Stentiford's lawyer says his client should have been tested because he is gay and was exposed to bodily fluids while working as a paramedic. By the time the disease was discovered, Stentiford's condition had progressed to AIDS. He suffered brain damage, which in turn ended his career as an attorney. “He had a brilliant future in front of him. They literally cut the legs out from under him,” his lawyer, David P. Angueira, said. “He lost his job. He lost his career. He lost his life.” Lawyers for the doctors didn’t respond Tuesday to requests for comment. Stentiford's lawyer says he lives in New York City and now controls AIDS-related symptoms with medication.
{ "task_name": "multi_news" }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace TicTacToe { /// <summary> /// This class represents a Tic-Tac-Toe game board. It includes logic /// to keep track of player turns and assign board squares to a player /// </summary> public class TicTacToeGame { public enum Players { Player1, Player2 }; protected bool isDraw = false; protected bool haveWinner; protected Board board; protected Stack<TicTacToeMove> moves; protected Players currentTurn = Players.Player1; // Player 1 goes first protected Board.Pieces player1Piece = Board.Pieces.X; // player 1 uses X and player 2 uses O by default protected Board.Pieces player2Piece = Board.Pieces.O; protected Board.Pieces winningPiece = Board.Pieces.Empty; protected Players winningPlayer; protected bool gameOver = false; /// <summary> /// Constructs a new TicTacToeGame using the default board pieces for player one and two /// </summary> public TicTacToeGame() : this(Board.Pieces.X, Board.Pieces.O) { } /// <summary> /// Constructs a new TicTacToe game using the specified player's pieces. /// /// </summary> /// <param name="player1Piece">Player one's piece</param> /// <param name="player2Piece">Player two's piece</param> public TicTacToeGame(Board.Pieces player1Piece, Board.Pieces player2Piece) { this.player1Piece = player1Piece; this.player2Piece = player2Piece; board = new Board(); moves = new Stack<TicTacToeMove>(); } /// <summary> /// Gets the Board associated with this game /// </summary> public Board GameBoard { get { return board; } } /// <summary> /// gets number of columns on the board /// </summary> public int Columns { get { return board.Columns; } } /// <summary> /// gets the number of rows on the game board /// </summary> public int Rows { get { return board.Rows; } } /// <summary> /// If there currently is a winner, this returns the the piece that has /// won. Otherwise it returns Pieces.Empty if there is no winner. /// </summary> public Board.Pieces WinningPiece { get { return winningPiece; } } /// <summary> /// Returns true if the game is over (if there is a winner or there is a draw) /// </summary> /// <returns>true if the game is over or false otherwise</returns> public bool IsGameOver() { return board.IsGameOver(); } /// <summary> /// Undoes the last move /// </summary> public void UndoLastMove() { TicTacToeMove lastMove = moves.Pop(); board.UndoMove(lastMove); SwapTurns(); } /// <summary> /// gets or sets Player 1's game piece /// </summary> public Board.Pieces Player1Piece { get { return player1Piece; } set { player1Piece = value; } } /// <summary> /// Gets or sets Player 2's game piece /// </summary> public Board.Pieces Player2Piece { get { return player2Piece; } set { player2Piece = value; } } /// <summary> /// Returns the player for whose turn it is /// </summary> public Players CurrentPlayerTurn { get { return this.currentTurn; } } /// <summary> /// Makes the specified move /// </summary> /// <param name="m">The TicTacToe move to be made</param> /// public void MakeMove(TicTacToeMove m) { MakeMove(m, GetPlayerWhoHasPiece(m.Piece)); } /// <summary> /// Makes the move for the specified player /// </summary> /// <param name="m">The move to make</param> /// <param name="p">The player making the move</param> public void MakeMove(TicTacToeMove m, Players p) { if (currentTurn != p) { throw new InvalidMoveException("You went out of turn!"); } if (!board.IsValidSquare(m.Position)) throw new InvalidMoveException("Pick a square on the board!"); board.MakeMove(m.Position, m.Piece); moves.Push(m); SwapTurns(); } /// <summary> /// This should not be called by clients. This is only for unit testing /// </summary> /// <param name="position">The position to take</param> /// <param name="p">The player who is taking the piece</param> public void TakeSquare(int position, Players p) { if (currentTurn != p) throw new InvalidMoveException("You tried to move out of turn!"); if (!board.IsValidSquare(position)) throw new InvalidMoveException(); board.MakeMove(position, GetPlayersPiece(p)); if (board.HasWinner()) winningPlayer = currentTurn; SwapTurns(); } // Returns the game piece for the specified player protected Board.Pieces GetPlayersPiece(Players p) { if (p == Players.Player1) return player1Piece; else return player2Piece; } // returns the Player who has the specified piece protected TicTacToeGame.Players GetPlayerWhoHasPiece(Board.Pieces piece) { if (piece == player1Piece) return Players.Player1; else return Players.Player2; } // Swap whose turn it is. // If X just moved we make it O's turn and // vice versa private void SwapTurns() { if (currentTurn == Players.Player1) currentTurn = Players.Player2; else currentTurn = Players.Player1; } } /// <summary> /// Represents a tic-tac-toe move /// </summary> public class TicTacToeMove { /// <summary> /// Constructs a TicTacToeMove /// </summary> /// <param name="position">The position to move to</param> /// <param name="piece">The piece that is moving</param> public TicTacToeMove(int position, Board.Pieces piece) { this.Position = position; this.Piece = piece; } /// <summary> /// gets or sets the position on the board /// </summary> public int Position { get; set; } /// <summary> /// Gets or sets the piece making this move /// </summary> public Board.Pieces Piece {get; set;} } /// <summary> /// An Exception representing an invalid move /// </summary> public class InvalidMoveException : Exception { public InvalidMoveException() : base() { } public InvalidMoveException(string msg) : base(msg) { } } }
{ "task_name": "lcc" }
# Copyright 2013-present Barefoot Networks, 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. # from mininet.net import Mininet from mininet.node import Switch, Host from mininet.log import setLogLevel, info, error, debug from mininet.moduledeps import pathCheck from sys import exit import os import tempfile import socket from time import sleep import subprocess import grpc import p4runtime_lib.bmv2 import p4runtime_lib.helper from p4runtime_lib.error_utils import printGrpcError from netstat import check_listening_on_port SWITCH_START_TIMEOUT = 10 # seconds def tableEntryToString(flow): if 'match' in flow: match_str = ['%s=%s' % (match_name, str(flow['match'][match_name])) for match_name in flow['match']] match_str = ', '.join(match_str) elif 'default_action' in flow and flow['default_action']: match_str = '(default action)' else: match_str = '(any)' params = ['%s=%s' % (param_name, str(flow['action_params'][param_name])) for param_name in flow['action_params']] params = ', '.join(params) return "%s: %s => %s(%s)" % ( flow['table'], match_str, flow['action_name'], params) # object hook for josn library, use str instead of unicode object # https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json def json_load_byteified(file_handle): return _byteify(json.load(file_handle, object_hook=_byteify), ignore_dicts=True) def _byteify(data, ignore_dicts=False): # if this is a unicode string, return its string representation if isinstance(data, unicode): return data.encode('utf-8') # if this is a list of values, return list of byteified values if isinstance(data, list): return [_byteify(item, ignore_dicts=True) for item in data] # if this is a dictionary, return dictionary of byteified keys and values # but only if we haven't already byteified it if isinstance(data, dict) and not ignore_dicts: return { _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True) for key, value in data.items() } # if it's anything else, return it in its original form return data class P4Host(Host): def config(self, **params): r = super(Host, self).config(**params) self.defaultIntf().rename("eth0") for off in ["rx", "tx", "sg"]: cmd = "/sbin/ethtool --offload %s %s off" % (self.defaultIntf().name, off) self.cmd(cmd) # disable IPv6 self.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1") self.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1") self.cmd("sysctl -w net.ipv6.conf.lo.disable_ipv6=1") return r def describe(self): print ("**********") print (self.name) print ("default interface: %s\t%s\t%s" %( self.defaultIntf().name, self.defaultIntf().IP(), self.defaultIntf().MAC() )) print ("**********") class P4Switch(Switch): """P4 virtual switch""" device_id = 0 def __init__(self, name, sw_path = None, json_path = None, thrift_port = None, pcap_dump = False, log_console = False, log_file = None, verbose = False, device_id = None, enable_debugger = False, **kwargs): Switch.__init__(self, name, **kwargs) assert(sw_path) assert(json_path) # make sure that the provided sw_path is valid pathCheck(sw_path) # make sure that the provided JSON file exists if not os.path.isfile(json_path): error("Invalid JSON file.\n") exit(1) self.sw_path = sw_path self.json_path = json_path self.verbose = verbose logfile = "/tmp/p4s.{}.log".format(self.name) self.output = open(logfile, 'w') self.thrift_port = thrift_port if check_listening_on_port(self.thrift_port): error('%s cannot bind port %d because it is bound by another process\n' % (self.name, self.grpc_port)) exit(1) self.pcap_dump = pcap_dump self.enable_debugger = enable_debugger self.log_console = log_console if log_file is not None: self.log_file = log_file else: self.log_file = "/tmp/p4s.{}.log".format(self.name) if device_id is not None: self.device_id = device_id P4Switch.device_id = max(P4Switch.device_id, device_id) else: self.device_id = P4Switch.device_id P4Switch.device_id += 1 self.nanomsg = "ipc:///tmp/bm-{}-log.ipc".format(self.device_id) @classmethod def setup(cls): pass def check_switch_started(self, pid): """While the process is running (pid exists), we check if the Thrift server has been started. If the Thrift server is ready, we assume that the switch was started successfully. This is only reliable if the Thrift server is started at the end of the init process""" while True: if not os.path.exists(os.path.join("/proc", str(pid))): return False if check_listening_on_port(self.thrift_port): return True sleep(0.5) def start(self, controllers): "Start up a new P4 switch" info("Starting P4 switch {}.\n".format(self.name)) args = [self.sw_path] for port, intf in self.intfs.items(): if not intf.IP(): args.extend(['-i', str(port) + "@" + intf.name]) if self.pcap_dump: args.append("--pcap %s" % self.pcap_dump) if self.thrift_port: args.extend(['--thrift-port', str(self.thrift_port)]) if self.nanomsg: args.extend(['--nanolog', self.nanomsg]) args.extend(['--device-id', str(self.device_id)]) P4Switch.device_id += 1 args.append(self.json_path) if self.enable_debugger: args.append("--debugger") if self.log_console: args.append("--log-console") info(' '.join(args) + "\n") pid = None with tempfile.NamedTemporaryFile() as f: # self.cmd(' '.join(args) + ' > /dev/null 2>&1 &') self.cmd(' '.join(args) + ' >' + self.log_file + ' 2>&1 & echo $! >> ' + f.name) pid = int(f.read()) debug("P4 switch {} PID is {}.\n".format(self.name, pid)) if not self.check_switch_started(pid): error("P4 switch {} did not start correctly.\n".format(self.name)) exit(1) info("P4 switch {} has been started.\n".format(self.name)) def stop(self): "Terminate P4 switch." self.output.flush() self.cmd('kill %' + self.sw_path) self.cmd('wait') self.deleteIntfs() def attach(self, intf): "Connect a data port" assert(0) def detach(self, intf): "Disconnect a data port" assert(0) class P4RuntimeSwitch(P4Switch): "BMv2 switch with gRPC support" next_grpc_port = 50051 next_thrift_port = 9090 def __init__(self, name, sw_path = None, enable_grpc = True, grpc_port = None, thrift_port = None, pcap_dump = False, log_console = False, start_controller = True, program = None, verbose = False, device_id = None, enable_debugger = False, cli_path = None, log_file = None, **kwargs): Switch.__init__(self, name, **kwargs) assert (sw_path) self.sw_path = sw_path # make sure that the provided sw_path is valid pathCheck(sw_path) self.cli_path = cli_path self.program = program self.enable_grpc = enable_grpc json_path = None p4info_path = None if self.program: json_path = self.program.json() if self.program.p4info(): p4info_path = self.program.p4info() if json_path is not None: # make sure that the provided JSON file exists if not os.path.isfile(json_path): error("Invalid JSON file.\n") exit(1) self.json_path = json_path else: self.json_path = None if p4info_path is not None: if not os.path.isfile(p4info_path): error("Invalid P4Info file.\n") exit(1) self.p4info_path = p4info_path else: self.p4info_path = None self.grpc_port = grpc_port if self.enable_grpc and grpc_port is None: self.grpc_port = P4RuntimeSwitch.next_grpc_port P4RuntimeSwitch.next_grpc_port += 1 if thrift_port is not None: self.thrift_port = thrift_port else: self.thrift_port = P4RuntimeSwitch.next_thrift_port P4RuntimeSwitch.next_thrift_port += 1 if enable_grpc and check_listening_on_port(self.grpc_port): error('%s cannot bind port %d because it is bound by another process\n' % (self.name, self.grpc_port)) exit(1) self.verbose = verbose logfile = "/tmp/p4app-logs/p4s.{}.log".format(self.name) self.output = open(logfile, 'w') self.pcap_dump = pcap_dump self.enable_debugger = enable_debugger self.log_console = log_console self.start_controller = start_controller if not self.program.supportsP4Runtime(): self.start_controller = False self.sw_conn = None if log_file is not None: self.log_file = log_file else: self.log_file = logfile if device_id is not None: self.device_id = device_id P4Switch.device_id = max(P4Switch.device_id, device_id) else: self.device_id = P4Switch.device_id P4Switch.device_id += 1 self.nanomsg = "ipc:///tmp/bm-{}-log.ipc".format(self.device_id) def check_switch_started(self, pid): for _ in range(SWITCH_START_TIMEOUT * 2): if not os.path.exists(os.path.join("/proc", str(pid))): return False if self.enable_grpc and check_listening_on_port(self.grpc_port): return True elif self.thrift_port and check_listening_on_port(self.thrift_port): return True sleep(0.5) def start(self, controllers): info("Starting P4 switch {}.\n".format(self.name)) args = [self.sw_path] for port, intf in self.intfs.items(): if not intf.IP(): args.extend(['-i', str(port) + "@" + intf.name]) if self.pcap_dump: args.append("--pcap %s" % self.pcap_dump) if self.nanomsg: args.extend(['--nanolog', self.nanomsg]) args.extend(['--device-id', str(self.device_id)]) P4Switch.device_id += 1 if self.json_path: args.append(self.json_path) else: args.append("--no-p4") if self.enable_debugger: args.append("--debugger") if self.log_console: args.append("--log-console") if self.thrift_port: args.append('--thrift-port ' + str(self.thrift_port)) if self.grpc_port: args.append("-- --grpc-server-addr 0.0.0.0:" + str(self.grpc_port)) cmd = ' '.join(args) info(cmd + "\n") pid = None with tempfile.NamedTemporaryFile() as f: self.cmd(cmd + ' >' + self.log_file + ' 2>&1 & echo $! >> ' + f.name) pid = int(f.read()) debug("P4 switch {} PID is {}.\n".format(self.name, pid)) if not self.check_switch_started(pid): error("P4 switch {} did not start correctly.\n".format(self.name)) exit(1) info("P4 switch {} has been started.\n".format(self.name)) if self.start_controller: self.sw_conn = p4runtime_lib.bmv2.Bmv2SwitchConnection( name=self.name, address='127.0.0.1:' + str(self.grpc_port), device_id=self.device_id, proto_dump_file='/tmp/p4app-logs/' + self.name + '-p4runtime-requests.txt') try: self.sw_conn.MasterArbitrationUpdate() except grpc.RpcError as e: printGrpcError(e) if self.p4info_path: self.loadP4Info() self.loadJSON() def stop(self): if self.sw_conn: self.sw_conn.shutdown() P4Switch.stop(self) def commands(self, cmd_list): if not self.thrift_port: raise Exception("Switch %s doesn't use Thrift, so there's no CLI support" % self.name) print('\n'.join(cmd_list)) p = subprocess.Popen([self.cli_path, '--thrift-port', str(self.thrift_port)], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, nostderr = p.communicate(input='\n'.join(cmd_list) + '\nEOF\n') print(stdout) raw_results = stdout.split('RuntimeCmd:')[1:len(cmd_list)+1] return raw_results def command(self, cmd): return self.commands([cmd])[0] def loadP4Info(self): self.p4info_helper = p4runtime_lib.helper.P4InfoHelper(self.p4info_path) def loadJSON(self): try: self.sw_conn.SetForwardingPipelineConfig(p4info=self.p4info_helper.p4info, bmv2_json_file_path=self.json_path) except grpc.RpcError as e: printGrpcError(e) def loadConf(self, sw_conf_or_filename): if isinstance(sw_conf_or_filename, dict): sw_conf = sw_conf_or_filename else: conf_path = os.path.join('/p4app', sw_conf_or_filename) with open(conf_path, 'r') as f: sw_conf = json_load_byteified(f) if 'p4info' in sw_conf: info('Using P4Info file %s...' % sw_conf['p4info']) self.p4info_path = os.path.join('/tmp/p4app-logs/', sw_conf['p4info']) self.loadP4Info() assert sw_conf['target'] == 'bmv2' if 'bmv2_json' in sw_conf: info("Setting pipeline config (%s)..." % sw_conf['bmv2_json']) self.json_path = os.path.join('/tmp/p4app-logs/', sw_conf['bmv2_json']) self.loadJSON() if 'table_entries' in sw_conf: info("Inserting %d table entries..." % len(sw_conf['table_entries'])) for entry in sw_conf['table_entries']: info(tableEntryToString(entry)) self.insertTableEntry(entry) def insertTableEntry(self, entry=None, table_name=None, match_fields=None, action_name=None, default_action=None, action_params=None, priority=None): if entry is not None: table_name = entry['table_name'] match_fields = entry.get('match_fields') # None if not found action_name = entry['action_name'] default_action = entry.get('default_action') # None if not found action_params = entry['action_params'] priority = entry.get('priority') # None if not found table_entry = self.p4info_helper.buildTableEntry( table_name=table_name, match_fields=match_fields, default_action=default_action, action_name=action_name, action_params=action_params, priority=priority) try: self.sw_conn.WriteTableEntry(table_entry) except grpc.RpcError as e: printGrpcError(e) def removeTableEntry(self, entry=None, table_name=None, match_fields=None, action_name=None, default_action=None, action_params=None, priority=None): if entry is not None: table_name = entry['table_name'] match_fields = entry.get('match_fields') # None if not found action_name = entry['action_name'] default_action = entry.get('default_action') # None if not found action_params = entry['action_params'] priority = entry.get('priority') # None if not found table_entry = self.p4info_helper.buildTableEntry( table_name=table_name, match_fields=match_fields, default_action=default_action, action_name=action_name, action_params=action_params, priority=priority) try: self.sw_conn.DeleteTableEntry(table_entry) except grpc.RpcError as e: printGrpcError(e) def addMulticastGroup(self, mgid=None, ports=None): group = self.p4info_helper.buildMulticastGroup(mgid=mgid, ports=ports) try: self.sw_conn.CreateMulticastGroup(group) except grpc.RpcError as e: printGrpcError(e) def deleteMulticastGroup(self, mgid=None, ports=None): group = self.p4info_helper.buildMulticastGroup(mgid=mgid, ports=ports) try: self.sw_conn.DeleteMulticastGroup(group) except grpc.RpcError as e: printGrpcError(e) def updateMulticastGroup(self, mgid=None, ports=None): group = self.p4info_helper.buildMulticastGroup(mgid=mgid, ports=ports) try: self.sw_conn.UpdateMulticastGroup(group) except grpc.RpcError as e: printGrpcError(e) def printTableEntries(self): """ Prints the table entries from all tables on the switch. :param p4info_helper: the P4Info helper :param sw: the switch connection """ print('\n----- Reading tables rules for %s -----' % self.sw_conn.name) for response in self.sw_conn.ReadTableEntries(): for entity in response.entities: entry = entity.table_entry table_name = self.p4info_helper.get_tables_name(entry.table_id) print ('%s: ' % table_name, end=' ') for m in entry.match: print(self.p4info_helper.get_match_field_name(table_name, m.field_id), end=' ') print('%r' % (self.p4info_helper.get_match_field_value(m),), end=' ') action = entry.action.action action_name = self.p4info_helper.get_actions_name(action.action_id) print('->', action_name, end=' ') for p in action.params: print(self.p4info_helper.get_action_param_name(action_name, p.param_id), end=' ') print('%r' % p.value, end=' ') print() def readCounter(self, counter_name, index): """ Reads the specified counter at the specified index from the switch. :param counter_name: the name of the counter from the P4 program :param index: the counter index """ for response in self.sw_conn.ReadCounters(self.p4info_helper.get_counters_id(counter_name), index): for entity in response.entities: counter = entity.counter_entry return counter.data.packet_count, counter.data.byte_count
{ "task_name": "lcc" }
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Deep Neural Network estimators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.contrib import layers from tensorflow.contrib.framework import deprecated from tensorflow.contrib.framework import deprecated_arg_values from tensorflow.contrib.framework.python.ops import variables as contrib_variables from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn import metric_spec from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators import prediction_key from tensorflow.contrib.learn.python.learn.utils import export from tensorflow.python.ops import nn from tensorflow.python.ops import partitioned_variables from tensorflow.python.ops import variable_scope from tensorflow.python.summary import summary # The default learning rate of 0.05 is a historical artifact of the initial # implementation, but seems a reasonable choice. _LEARNING_RATE = 0.05 def _get_feature_dict(features): if isinstance(features, dict): return features return {"": features} def _get_optimizer(optimizer): if callable(optimizer): return optimizer() else: return optimizer def _add_hidden_layer_summary(value, tag): summary.scalar("%s_fraction_of_zero_values" % tag, nn.zero_fraction(value)) summary.histogram("%s_activation" % tag, value) def _dnn_model_fn(features, labels, mode, params, config=None): """Deep Neural Net model_fn. Args: features: `Tensor` or dict of `Tensor` (depends on data passed to `fit`). labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype `int32` or `int64` in the range `[0, n_classes)`. mode: Defines whether this is training, evaluation or prediction. See `ModeKeys`. params: A dict of hyperparameters. The following hyperparameters are expected: * head: A `_Head` instance. * hidden_units: List of hidden units per layer. * feature_columns: An iterable containing all the feature columns used by the model. * optimizer: string, `Optimizer` object, or callable that defines the optimizer to use for training. If `None`, will use the Adagrad optimizer with a default learning rate of 0.05. * activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. * dropout: When not `None`, the probability we will drop out a given coordinate. * gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. * embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. * input_layer_min_slice_size: Optional. The min slice size of input layer partitions. If not provided, will use the default of 64M. config: `RunConfig` object to configure the runtime settings. Returns: predictions: A dict of `Tensor` objects. loss: A scalar containing the loss of the step. train_op: The op for training. """ head = params["head"] hidden_units = params["hidden_units"] feature_columns = params["feature_columns"] optimizer = params.get("optimizer") or "Adagrad" activation_fn = params.get("activation_fn") dropout = params.get("dropout") gradient_clip_norm = params.get("gradient_clip_norm") input_layer_min_slice_size = ( params.get("input_layer_min_slice_size") or 64 << 20) num_ps_replicas = config.num_ps_replicas if config else 0 embedding_lr_multipliers = params.get("embedding_lr_multipliers", {}) features = _get_feature_dict(features) parent_scope = "dnn" partitioner = partitioned_variables.min_max_variable_partitioner( max_partitions=num_ps_replicas) with variable_scope.variable_scope( parent_scope, values=tuple(six.itervalues(features)), partitioner=partitioner): input_layer_partitioner = ( partitioned_variables.min_max_variable_partitioner( max_partitions=num_ps_replicas, min_slice_size=input_layer_min_slice_size)) with variable_scope.variable_scope( "input_from_feature_columns", values=tuple(six.itervalues(features)), partitioner=input_layer_partitioner) as input_layer_scope: net = layers.input_from_feature_columns( columns_to_tensors=features, feature_columns=feature_columns, weight_collections=[parent_scope], scope=input_layer_scope) for layer_id, num_hidden_units in enumerate(hidden_units): with variable_scope.variable_scope( "hiddenlayer_%d" % layer_id, values=(net,)) as hidden_layer_scope: net = layers.fully_connected( net, num_hidden_units, activation_fn=activation_fn, variables_collections=[parent_scope], scope=hidden_layer_scope) if dropout is not None and mode == model_fn.ModeKeys.TRAIN: net = layers.dropout(net, keep_prob=(1.0 - dropout)) _add_hidden_layer_summary(net, hidden_layer_scope.name) with variable_scope.variable_scope( "logits", values=(net,)) as logits_scope: logits = layers.fully_connected( net, head.logits_dimension, activation_fn=None, variables_collections=[parent_scope], scope=logits_scope) _add_hidden_layer_summary(logits, logits_scope.name) def _train_op_fn(loss): """Returns the op to optimize the loss.""" return optimizers.optimize_loss( loss=loss, global_step=contrib_variables.get_global_step(), learning_rate=_LEARNING_RATE, optimizer=_get_optimizer(optimizer), gradient_multipliers=( dnn_linear_combined._extract_embedding_lr_multipliers( # pylint: disable=protected-access embedding_lr_multipliers, parent_scope, input_layer_scope.name)), clip_gradients=gradient_clip_norm, name=parent_scope, # Empty summaries to prevent optimizers from logging training_loss. summaries=[]) return head.create_model_fn_ops( features=features, mode=mode, labels=labels, train_op_fn=_train_op_fn, logits=logits) class DNNClassifier(estimator.Estimator): """A classifier for TensorFlow DNN models. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) estimator = DNNClassifier( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNClassifier( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) # Input builders def input_fn_train: # returns x, y (where y represents label's class index). pass estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, y (where y represents label's class index). pass estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) # returns predicted labels (i.e. label's class index). ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=False, config=None, feature_engineering_fn=None, embedding_lr_multipliers=None, input_layer_min_slice_size=None): """Initializes a DNNClassifier instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. n_classes: number of label classes. Default is binary classification. It must be greater than 1. Note: Class labels are integers representing the class index (i.e. values from 0 to n_classes-1). For arbitrary label values (e.g. string labels), convert to class indices first. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `tf.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. input_layer_min_slice_size: Optional. The min slice size of input layer partitions. If not provided, will use the default of 64M. Returns: A `DNNClassifier` estimator. Raises: ValueError: If `n_classes` < 2. """ self._feature_columns = tuple(feature_columns or []) super(DNNClassifier, self).__init__( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head_lib.multi_class_head( n_classes, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias), "hidden_units": hidden_units, "feature_columns": self._feature_columns, "optimizer": optimizer, "activation_fn": activation_fn, "dropout": dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, "input_layer_min_slice_size": input_layer_min_slice_size, }, feature_engineering_fn=feature_engineering_fn) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) @deprecated_arg_values( "2017-03-01", "Please switch to predict_classes, or set `outputs` argument.", outputs=None) def predict(self, x=None, input_fn=None, batch_size=None, outputs=None, as_iterable=True): """Returns predictions for given features. By default, returns predicted classes. But this default will be dropped soon. Users should either pass `outputs`, or call `predict_classes` method. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. outputs: list of `str`, name of the output to predict. If `None`, returns classes. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes with shape [batch_size] (or an iterable of predicted classes if as_iterable is True). Each predicted class is represented by its class index (i.e. integer from 0 to n_classes-1). If `outputs` is set, returns a dict of predictions. """ if not outputs: return self.predict_classes( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable) return super(DNNClassifier, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=outputs, as_iterable=as_iterable) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict_classes(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns predicted classes for given features. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes with shape [batch_size] (or an iterable of predicted classes if as_iterable is True). Each predicted class is represented by its class index (i.e. integer from 0 to n_classes-1). """ key = prediction_key.PredictionKey.CLASSES preds = super(DNNClassifier, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key].reshape(-1) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict_proba(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns predicted probabilities for given features. Args: x: features. input_fn: Input function. If set, x and y must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted probabilities with shape [batch_size, n_classes] (or an iterable of predicted probabilities if as_iterable is True). """ key = prediction_key.PredictionKey.PROBABILITIES preds = super(DNNClassifier, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key] @deprecated("2017-03-25", "Please use Estimator.export_savedmodel() instead.") def export(self, export_dir, input_fn=None, input_feature_key=None, use_deprecated_input_fn=True, signature_fn=None, default_batch_size=1, exports_to_keep=None): """See BaseEstimator.export.""" def default_input_fn(unused_estimator, examples): return layers.parse_feature_columns_from_examples(examples, self._feature_columns) return super(DNNClassifier, self).export( export_dir=export_dir, input_fn=input_fn or default_input_fn, input_feature_key=input_feature_key, use_deprecated_input_fn=use_deprecated_input_fn, signature_fn=(signature_fn or export.classification_signature_fn_with_prob), prediction_key=prediction_key.PredictionKey.PROBABILITIES, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep) class DNNRegressor(estimator.Estimator): """A regressor for TensorFlow DNN models. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) estimator = DNNRegressor( feature_columns=[sparse_feature_a, sparse_feature_b], hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNRegressor( feature_columns=[sparse_feature_a, sparse_feature_b], hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) # Input builders def input_fn_train: # returns x, y pass estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, y pass estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, hidden_units, feature_columns, model_dir=None, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=False, config=None, feature_engineering_fn=None, label_dimension=1, embedding_lr_multipliers=None, input_layer_min_slice_size=None): """Initializes a `DNNRegressor` instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A `float` > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `tf.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. label_dimension: Number of regression targets per example. This is the size of the last dimension of the labels and logits `Tensor` objects (typically, these have shape `[batch_size, label_dimension]`). embedding_lr_multipliers: Optional. A dictionary from `EbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. input_layer_min_slice_size: Optional. The min slice size of input layer partitions. If not provided, will use the default of 64M. Returns: A `DNNRegressor` estimator. """ self._feature_columns = tuple(feature_columns or []) super(DNNRegressor, self).__init__( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head_lib.regression_head( label_dimension=label_dimension, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias), "hidden_units": hidden_units, "feature_columns": self._feature_columns, "optimizer": optimizer, "activation_fn": activation_fn, "dropout": dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, "input_layer_min_slice_size": input_layer_min_slice_size, }, feature_engineering_fn=feature_engineering_fn) def evaluate(self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None, checkpoint_path=None, hooks=None): """See evaluable.Evaluable.""" # TODO(zakaria): remove once deprecation is finished (b/31229024) custom_metrics = {} if metrics: for key, metric in six.iteritems(metrics): if (not isinstance(metric, metric_spec.MetricSpec) and not isinstance(key, tuple)): custom_metrics[(key, prediction_key.PredictionKey.SCORES)] = metric else: custom_metrics[key] = metric return super(DNNRegressor, self).evaluate( x=x, y=y, input_fn=input_fn, feed_fn=feed_fn, batch_size=batch_size, steps=steps, metrics=custom_metrics, name=name, checkpoint_path=checkpoint_path, hooks=hooks) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) @deprecated_arg_values( "2017-03-01", "Please switch to predict_scores, or set `outputs` argument.", outputs=None) def predict(self, x=None, input_fn=None, batch_size=None, outputs=None, as_iterable=True): """Returns predictions for given features. By default, returns predicted scores. But this default will be dropped soon. Users should either pass `outputs`, or call `predict_scores` method. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. outputs: list of `str`, name of the output to predict. If `None`, returns scores. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted scores (or an iterable of predicted scores if as_iterable is True). If `label_dimension == 1`, the shape of the output is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`. If `outputs` is set, returns a dict of predictions. """ if not outputs: return self.predict_scores( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable) return super(DNNRegressor, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=outputs, as_iterable=as_iterable) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict_scores(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns predicted scores for given features. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted scores (or an iterable of predicted scores if as_iterable is True). If `label_dimension == 1`, the shape of the output is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`. """ key = prediction_key.PredictionKey.SCORES preds = super(DNNRegressor, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key] @deprecated("2017-03-25", "Please use Estimator.export_savedmodel() instead.") def export(self, export_dir, input_fn=None, input_feature_key=None, use_deprecated_input_fn=True, signature_fn=None, default_batch_size=1, exports_to_keep=None): """See BaseEstimator.export.""" def default_input_fn(unused_estimator, examples): return layers.parse_feature_columns_from_examples(examples, self._feature_columns) return super(DNNRegressor, self).export( export_dir=export_dir, input_fn=input_fn or default_input_fn, input_feature_key=input_feature_key, use_deprecated_input_fn=use_deprecated_input_fn, signature_fn=signature_fn or export.regression_signature_fn, prediction_key=prediction_key.PredictionKey.SCORES, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep) class DNNEstimator(estimator.Estimator): """A Estimator for TensorFlow DNN models with user specified _Head. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) To create a DNNEstimator for binary classification, where estimator = DNNEstimator( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], head=tf.contrib.learn.multi_class_head(n_classes=2), hidden_units=[1024, 512, 256]) If your label is keyed with "y" in your labels dict, and weights are keyed with "w" in features dict, and you want to enable centered bias, head = tf.contrib.learn.multi_class_head( n_classes=2, label_name="x", weight_column_name="w", enable_centered_bias=True) estimator = DNNEstimator( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], head=head, hidden_units=[1024, 512, 256]) # Input builders def input_fn_train: # returns x, y (where y represents label's class index). pass estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, y (where y represents label's class index). pass estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) # returns predicted labels (i.e. label's class index). ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, head, hidden_units, feature_columns, model_dir=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, config=None, feature_engineering_fn=None, embedding_lr_multipliers=None, input_layer_min_slice_size=None): """Initializes a `DNNEstimator` instance. Args: head: `Head` instance. hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `tf.clip_by_global_norm` for more details. config: `RunConfig` object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. input_layer_min_slice_size: Optional. The min slice size of input layer partitions. If not provided, will use the default of 64M. Returns: A `DNNEstimator` estimator. """ super(DNNEstimator, self).__init__( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head, "hidden_units": hidden_units, "feature_columns": feature_columns, "optimizer": optimizer, "activation_fn": activation_fn, "dropout": dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, "input_layer_min_slice_size": input_layer_min_slice_size, }, feature_engineering_fn=feature_engineering_fn)
{ "task_name": "lcc" }