['B-CALLTYPE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET']


['B-CALLTYPE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET', 'I-TARGET']


['B-CALLTYPE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'I-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET', 'I-TARGET', 'I-TARGET']


['B-CALLTYPE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET']


['B-BUYPRICE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET', 'I-TARGET', 'I-TARGET']


['B-CALLTYPE', 'B-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'I-STOPLOSS', 'B-TARGET', 'I-TARGET', 'I-TARGET', 'I-TARGET']


['B-INSTRUMENT', 'I-INSTRUMENT', 'I-INSTRUMENT', 'B-BUYPRICE', 'I-BUYPRICE', 'B-STOPLOSS', 'O', 'B-TARGET', 'I-TARGET', 'I-TARGET']


public void brew() {

    }


void off();


boolean isHot();


public static void main(String[] args) {
    }


@Override public void off() {

    }


Sa o pupi in k..r, batran si prost


Martin Martin Normal. De acolo iese"ciubucul".


Top 5 DMV Mistakes and How to Avoid Them#3_0

Context:
Many DMV customers make easily avoidable mistakes that cause them significant problems, including encounters with law enforcement and impounded vehicles. Because we see customers make these mistakes over and over again , we are issuing this list of the top five DMV mistakes and how to avoid them.

1. Forgetting to Update Address
By statute , you must report a change of address to DMV within ten days of moving. That is the case for the address associated with your license, as well as all the addresses associated with each registered vehicle, which may differ. It is not sufficient to only: write your new address on the back of your old license; tell the United States Postal Service; or inform the police officer writing you a ticket. If you fail to keep your address current , you will miss a suspension order and may be charged with operating an unregistered vehicle and/or aggravated unlicensed operation, both misdemeanors. This really happens , but the good news is this is a problem that is easily avoidable. Learn more about how to change the address on your license and registrations [1 ]

2. Leaving the State Without Notifying DMV
States communicate with each other , so when you move to another state, be sure to tie up any loose ends regarding your New York State license or registration. That means resolving any unanswered tickets, suspensions or revocations, and surrendering your license plates to NYS when you get to your new home state. A license suspension or revocation here could mean that your new home state will not issue you a license there. Remember , it is important to notify DMV of your new address so that any possible mail correspondence can reach you. Also , turning in your plates is important to avoid an insurance lapse.

3. Letting Insurance Lapse
Because we all pay indirectly for crashes involving uninsured motorists , New York State requires every motorist to maintain auto insurance every single day a vehicle is registered. DMV works with insurance companies to electronically monitor your insurance coverage , and we know when coverage is dropped for any reason. When that happens , we mail you an insurance inquiry letter to allow you to clear up the problem. We send 500,000 inquiry letters a year. If the inquiry letter does not resolve the problem , we must suspend the vehicle registration and , if it persists, your driver license!We suspend 300,000 registrations a year for failure to maintain insurance. If you fail to maintain an updated address with us , you won t learn that you have an insurance problem , and we will suspend your registration and license. Make sure you turn in your vehicle s license plates at DMV before you cancel your insurance policy. Insurance policies must be from a company licensed in New York State. Learn more about Insurances Lapes [2] and How to Surrender your Plates [3 ]

4. Understanding how Much Traffic Points Cost
DMV maintains a point system to track dangerous drivers. Often , motorists convicted of a traffic ticket feel they have resolved all their motoring issues with the local court, but later learn that the Driver Responsibility Assessment DRA is a separate DMV charge based on the total points they accumulate. The $300 DRA fee can be paid in $100 annual installments over three years. Motorists who fail to maintain an updated address with DMV may resolve their tickets with the court, but never receive their DRA assessment because we do not have their new address on record. Failure to pay the DRA will result in a suspended license. Learn more about About the NYS Driver Point System [4] and how to Pay Driver Responsibility Assessment [5 ]

5. Not Bringing Proper Documentation to DMV Office
About ten percent of customers visiting a DMV office do not bring what they need to complete their transaction, and have to come back a second time to finish their business. This can be as simple as not bringing sufficient funds to pay for a license renewal or not having the proof of auto insurance required to register a car. Better yet , don t visit a DMV office at all, and see if your transaction can be performed online, like an address change, registration renewal, license renewal, replacing a lost title, paying a DRA or scheduling a road test. Our award - winning website is recognized as one of the best in the nation. It has all the answers you need to efficiently perform any DMV transaction. Consider signing up for our MyDMV service, which offers even more benefits. Sign up or log into MyDMV [6 ]

Question: Hello, I forgot o update my address, can you help me with that?[SEP]

Answer: you must report a change of address to DMV within ten days of moving. That is the case for the address associated with your license, as well as all the addresses associated with each registered vehicle, which may differ.

hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.


Question: Can I do my DMV transactions online?[SEP]agent: hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.||user: Hello, I forgot o update my address, can you help me with that?

Answer: Sign up or log into MyDMV [6 ]

Yes, you can sign up for MyDMV for all the online transactions needed.


Registration suspensions for failure to pay tolls#3_0

Context:
What is a suspension for failure to pay tolls?
If you do not pay a required toll, fee or other charge to a tolling authority, which operates a toll highway, bridge and/or tunnel facility, your registration may be suspended.

Who issues toll violations?
A tolling authority , which includes the New York State Thruway Authority, the Triborough Bridge and Tunnel Authority MTA Bridges and Tunnels and the Port Authority of New York and New Jersey.

What happens if I don t pay a toll?
If you fail to pay tolls, fees or other charges in relation to 3 or more tolling violations, all committed within 5 years, or fail to pay $200 in tolls accumulated within 5 years, if the violations occurred in a commercial vehicle, or fail to have them dismissed or transferred , the NYS Department of Motor Vehicles, " DMV " may send you a Notice of Registration Suspension. The notice will advise you that if you pay all of the tolls, fees or other charges owed to the tolling authority, or have them dismissed or transferred, the suspension will not take effect. You also have the right to a hearing before the DMV. If you request a DMV hearing , the suspension is placed on hold pending the outcome of the hearing.

What is the purpose of a DMV hearing?
The purpose of the hearing is to determine whether the tolling authority notified you that you failed to pay tolls, fees or other charges related to 3 or more violations of the Authority s toll collection regulations, all such violations committed within a 5 year period, or failed to pay $200 in tolls accumulated within 5 years, if the violations occurred in a commercial vehicle, or failed to have them dismissed or transferred. At the hearing , you may NOT dispute whether you evaded a toll and/or failed to pay tolls, fees or other charges. You must raise those issues with the tolling authority outside of the hearing.

Must I appear for the hearing?
As the Notice of Registration Suspension indicates , you may request an in - person DMV hearing or you may request a hearing by affidavit this is a hearing on paper. The Notice of Registration Suspension provides instructions about how to submit the affidavit to DMV. If you submit the affidavit , you will not have to appear at a DMV hearing. At an in - person DMV hearing , you may be represented by an attorney. If you request a DMV hearing and do not appear or submit your affidavit , your registration will be suspended immediately.

How can I respond to a tolling authority about a non-payment of tolls?
* * * DO NOT contact the New York State DMV to dispute whether you violated a toll regulation or failed to pay the toll, fees or other charges. *** You may contact the Customer Service Center and speak with a customer service specialist. Each tolling authority has a Customer Service Center and they can provide you information on your outstanding violation. To dispute an allegation that you violated a toll regulation or failed to pay the toll, fees or other charges , please contact the tolling authority listed on the Notice of Registration Suspension. Either mail : E - ZPass New York / DMV Registration Suspension PO Box 149005 Staten Island, NY 10314 - 9005 Or call the tolling authority at : New York State Thruway Authority at 718 - 313 - 9414 , Metropolitan Transit Authority at 718 313 - 9424 , & Port Authority of New York and New Jersey at 718 - 313 - 9425 There are several ways that your violations can be paid : By Mail send your check or money order no cash to : E - ZPass New York, DMV Registration Suspension, P.O. Box 149005 , Staten Island , NY 10314 - 9005. By Phone call the Customer Service Center based on the tolling authority listed on the Notice of Registration Suspension. Provide the customer service specialist with the license plate number listed on the Notice of Registration Suspension. Accepted payment methods are credit card, debit card, and bank account debit. Below is the contact information : New York State Thruway Authority : 718 - 313 - 9414 Metropolitan Transit Authority : 718 313 - 9424 Port Authority of New York and New Jersey : 718 - 313 - 9425 In Person visit one of the E - ZPass Customer Service walk - in centers. Locations and hours of operation can be found at www.e-zpassny.com/en/about/csc.shtml [1]. Online Visit the EZPass website [2] for information about how to pay a toll online. Online , you can also check the status of a violation or attempt to resolve a violation. * * * DO NOT contact the New York State DMV to dispute whether you violated a toll regulation or failed to pay the toll, fees or other charges. ***

Question: You've got it. Another query about DMV. What happens if you seek a hearing with the DMV?[SEP]agent: Yes, you can sign up for MyDMV for all the online transactions needed.||user: Can I do my DMV transactions online?||agent: hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.||user: Hello, I forgot o update my address, can you help me with that?

Answer: the suspension is placed on hold pending the outcome of the hearing.


Question: Besides that, will I receive a notice?[SEP]agent: the suspension is placed on hold pending the outcome of the hearing||user: You've got it. Another query about DMV. What happens if you seek a hearing with the DMV?||agent: Yes, you can sign up for MyDMV for all the online transactions needed.||user: Can I do my DMV transactions online?||agent: hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.||user: Hello, I forgot o update my address, can you help me with that?

Answer: the NYS Department of Motor Vehicles, " DMV " may send you a Notice of Registration Suspension. The notice will advise you that if you pay all of the tolls, fees or other charges owed to the tolling authority, or have them dismissed or transferred, the suspension will not take effect. You also have the right to a hearing before the DMV.

the NYS Department of Motor Vehicles , " DMV " may send you a Notice of Registration Suspension


Question: If you submit the affidavit?[SEP]agent:  the NYS Department of Motor Vehicles , " DMV " may send you a Notice of Registration Suspension||user: Besides that, will I receive a notice?||agent: the suspension is placed on hold pending the outcome of the hearing||user: You've got it. Another query about DMV. What happens if you seek a hearing with the DMV?||agent: Yes, you can sign up for MyDMV for all the online transactions needed.||user: Can I do my DMV transactions online?||agent: hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.||user: Hello, I forgot o update my address, can you help me with that?

Answer: you will not have to appear at a DMV hearing.

you will not have to appear at a DMV hearing


Question: How can I respond to a tolling authority about a non-payment of tolls?[SEP]agent: you will not have to appear at a DMV hearing||user: If you submit the affidavit?||agent:  the NYS Department of Motor Vehicles , " DMV " may send you a Notice of Registration Suspension||user: Besides that, will I receive a notice?||agent: the suspension is placed on hold pending the outcome of the hearing||user: You've got it. Another query about DMV. What happens if you seek a hearing with the DMV?||agent: Yes, you can sign up for MyDMV for all the online transactions needed.||user: Can I do my DMV transactions online?||agent: hi, you have to report any change of address to DMV within 10 days after moving. You should do this both for the address associated with your license and all the addresses associated with all your vehicles.||user: Hello, I forgot o update my address, can you help me with that?

Answer: * * * DO NOT contact the New York State DMV to dispute whether you violated a toll regulation or failed to pay the toll, fees or other charges. ***

DO NOT contact the New York State DMV to dispute whether you violated a toll regulation or failed to pay the toll , fees or other charges


Question: Will you keep me informed about when my insurance is about to lapse?[SEP]

Answer: Because we all pay indirectly for crashes involving uninsured motorists , New York State requires every motorist to maintain auto insurance every single day a vehicle is registered. DMV works with insurance companies to electronically monitor your insurance coverage ,

Yes. The New York State requires every motorist to maintain their insurance up to date so we at DMV make sure to inform you if you have any problem with your insurance.


Question: Is it needed that my address is always up to date with you guys?[SEP]agent: Yes. The New York State requires every motorist to maintain their insurance up to date so we at DMV make sure to inform you if you have any problem with your insurance.||user: Will you keep me informed about when my insurance is about to lapse?

Answer: you won t learn that you have an insurance problem , and we will suspend your registration and license. Make sure you turn in your vehicle s license plates at DMV before you cancel your insurance policy.

Yes, It is required. If not we won't be able to keep you informed about your insurance and we'll suspend your registration and license. You should make sure to turn in your vehicle's license plate before canceling your insurance policy


Question: for the suspension to be put on hold until the result is known. Isn't there a chance for a hearing? May I at the very least request a hearing with the DMV?[SEP]agent: Yes, It is required. If not we won't be able to keep you informed about your insurance and we'll suspend your registration and license. You should make sure to turn in your vehicle's license plate before canceling your insurance policy||user: Is it needed that my address is always up to date with you guys?||agent: Yes. The New York State requires every motorist to maintain their insurance up to date so we at DMV make sure to inform you if you have any problem with your insurance.||user: Will you keep me informed about when my insurance is about to lapse?

Answer: the NYS Department of Motor Vehicles, " DMV " may send you a Notice of Registration Suspension. The notice will advise you that if you pay all of the tolls, fees or other charges owed to the tolling authority, or have them dismissed or transferred, the suspension will not take effect. You also have the right to a hearing before the DMV.

Yes, you also have the right to a hearing before the DMV.


Question: And what effect can the hearing have?[SEP]agent: Yes, you also have the right to a hearing before the DMV.||user: for the suspension to be put on hold until the result is known. Isn't there a chance for a hearing? May I at the very least request a hearing with the DMV?||agent: Yes, It is required. If not we won't be able to keep you informed about your insurance and we'll suspend your registration and license. You should make sure to turn in your vehicle's license plate before canceling your insurance policy||user: Is it needed that my address is always up to date with you guys?||agent: Yes. The New York State requires every motorist to maintain their insurance up to date so we at DMV make sure to inform you if you have any problem with your insurance.||user: Will you keep me informed about when my insurance is about to lapse?

Answer: The purpose of the hearing is to determine whether the tolling authority notified you that you failed to pay tolls, fees or other charges related to 3 or more violations of the Authority s toll collection regulations, all such violations committed within a 5 year period, or failed to pay $200 in tolls accumulated within 5 years, if the violations occurred in a commercial vehicle, or failed to have them dismissed or transferred. At the hearing , you may NOT dispute whether you evaded a toll and/or failed to pay tolls, fees or other charges.

The purpose of the hearing is to determine whether the tolling authority notified you that you failed to pay tolls, fees or other charges related to 3 or more violations of the Authority's toll collection regulations, all such violations committed within a 5 year period, or failed to pay $ 200 in tolls accumulated within 5 years, if the violations occurred in a commercial vehicle, or failed to have them dismissed or transferred. At the hearing, you may NOT dispute whether you evaded a toll and/or failed to pay tolls, fees or other charges.


Context: The Yuan undertook extensive public works. Among Kublai Khan's top engineers and scientists was the astronomer Guo Shoujing, who was tasked with many public works projects and helped the Yuan reform the lunisolar calendar to provide an accuracy of 365.2425 days of the year, which was only 26 seconds off the modern Gregorian calendar's measurement. Road and water communications were reorganized and improved. To provide against possible famines, granaries were ordered built throughout the empire. The city of Beijing was rebuilt with new palace grounds that included artificial lakes, hills and mountains, and parks. During the Yuan period, Beijing became the terminus of the Grand Canal of China, which was completely renovated. These commercially oriented improvements encouraged overland and maritime commerce throughout Asia and facilitated direct Chinese contacts with Europe. Chinese travelers to the West were able to provide assistance in such areas as hydraulic engineering. Contacts with the West also brought the introduction to China of a major food crop, sorghum, along with other foreign food products and methods of preparation.

Question: What did Kublai do to prevent famines?


Context: The Taliban were spawned by the thousands of madrasahs the Deobandi movement established for impoverished Afghan refugees and supported by governmental and religious groups in neighboring Pakistan. The Taliban differed from other Islamist movements to the point where they might be more properly described as Islamic fundamentalist or neofundamentalist, interested in spreading "an idealized and systematized version of conservative tribal village customs" under the label of Sharia to an entire country. Their ideology was also described as being influenced by Wahhabism, and the extremist jihadism of their guest Osama bin Laden.

Question: Who influenced the Taliban's ideology?

Osama bin Laden
Osama bin Laden
Osama bin Laden


Context: Virtually all nuclear power plants generate electricity by heating water to provide steam that drives a turbine connected to an electrical generator. Nuclear-powered ships and submarines either use a steam turbine directly for main propulsion, with generators providing auxiliary power, or else employ turbo-electric transmission, where the steam drives a turbo generator set with propulsion provided by electric motors. A limited number of steam turbine railroad locomotives were manufactured. Some non-condensing direct-drive locomotives did meet with some success for long haul freight operations in Sweden and for express passenger work in Britain, but were not repeated. Elsewhere, notably in the U.S.A., more advanced designs with electric transmission were built experimentally, but not reproduced. It was found that steam turbines were not ideally suited to the railroad environment and these locomotives failed to oust the classic reciprocating steam unit in the way that modern diesel and electric traction has done.[citation needed]

Question: What is it called when steam propels a turbo generator with electric motor propulsion?

turbo-electric transmission,
turbo-electric transmission
turbo-electric transmission


Context: Harvard's 209-acre (85 ha) main campus is centered on Harvard Yard in Cambridge, about 3 miles (5 km) west-northwest of the State House in downtown Boston, and extends into the surrounding Harvard Square neighborhood. Harvard Yard itself contains the central administrative offices and main libraries of the university, academic buildings including Sever Hall and University Hall, Memorial Church, and the majority of the freshman dormitories. Sophomore, junior, and senior undergraduates live in twelve residential Houses, nine of which are south of Harvard Yard along or near the Charles River. The other three are located in a residential neighborhood half a mile northwest of the Yard at the Quadrangle (commonly referred to as the Quad), which formerly housed Radcliffe College students until Radcliffe merged its residential system with Harvard. Each residential house contains rooms for undergraduates, House masters, and resident tutors, as well as a dining hall and library. The facilities were made possible by a gift from Yale University alumnus Edward Harkness.

Question: How many residential dorms house upper class, sophomore, Jr, and Sr students?


Context: All of these processes do not necessarily occur in a single environment, and do not necessarily occur in a single order. The Hawaiian Islands, for example, consist almost entirely of layered basaltic lava flows. The sedimentary sequences of the mid-continental United States and the Grand Canyon in the southwestern United States contain almost-undeformed stacks of sedimentary rocks that have remained in place since Cambrian time. Other areas are much more geologically complex. In the southwestern United States, sedimentary, volcanic, and intrusive rocks have been metamorphosed, faulted, foliated, and folded. Even older rocks, such as the Acasta gneiss of the Slave craton in northwestern Canada, the oldest known rock in the world have been metamorphosed to the point where their origin is undiscernable without laboratory analysis. In addition, these processes can occur in stages. In many places, the Grand Canyon in the southwestern United States being a very visible example, the lower rock units were metamorphosed and deformed, and then deformation ended and the upper, undeformed units were deposited. Although any amount of rock emplacement and rock deformation can occur, and they can occur any number of times, these concepts provide a guide to understanding the geological history of an area.

Question: What has happened to the the rock in the Grand Canyon that is the oldest rock in the world?


Context: Cultural imperialism is when a country's influence is felt in social and cultural circles, i.e. its soft power, such that it changes the moral, cultural and societal worldview of another. This is more than just "foreign" music, television or film becoming popular with young people, but that popular culture changing their own expectations of life and their desire for their own country to become more like the foreign country depicted. For example, depictions of opulent American lifestyles in the soap opera Dallas during the Cold War changed the expectations of Romanians; a more recent example is the influence of smuggled South Korean drama series in North Korea. The importance of soft power is not lost on authoritarian regimes, fighting such influence with bans on foreign popular culture, control of the internet and unauthorised satellite dishes etc. Nor is such a usage of culture recent, as part of Roman imperialism local elites would be exposed to the benefits and luxuries of Roman culture and lifestyle, with the aim that they would then become willing participants.

Question: Which American did not show changed the views of Romanians during the cold war?


Context: One of the claimants of the English throne opposing William the Conqueror, Edgar Atheling, eventually fled to Scotland. King Malcolm III of Scotland married Edgar's sister Margaret, and came into opposition to William who had already disputed Scotland's southern borders. William invaded Scotland in 1072, riding as far as Abernethy where he met up with his fleet of ships. Malcolm submitted, paid homage to William and surrendered his son Duncan as a hostage, beginning a series of arguments as to whether the Scottish Crown owed allegiance to the King of England.

Question: Who was Margaret's brother?


Context: Between Bingen and Bonn, the Middle Rhine flows through the Rhine Gorge, a formation which was created by erosion. The rate of erosion equaled the uplift in the region, such that the river was left at about its original level while the surrounding lands raised. The gorge is quite deep and is the stretch of the river which is known for its many castles and vineyards. It is a UNESCO World Heritage Site (2002) and known as "the Romantic Rhine", with more than 40 castles and fortresses from the Middle Ages and many quaint and lovely country villages.

Question: What flows after Bingen and Bonn?


AIDS: definition and guidelines for the health professional.

AIDS is a lethal infectious disease that must certainly be dealt with carefully, but through conscientious application of well-established procedures and techniques, health care professionals may provide the best possible care to the patients suffering the ravages of this disease without undue risk to themselves or their loved ones.

There is no reason to believe that caring for the AIDS patient is any more dangerous than caring for a patient with any infectious disease; by utilizing already established safety precautions, we can deal with this situation efficiently and confidently.


Q:

How to use ECS and Lambda microservices within the same API?

I am trying to setup a microservice architecture on AWS, each microservice is a REST API.

Some of the services are running on ECS using Fargate and some of the services are running as a set of lambdas.

I am trying to have each api route resolve to the correct service, whether it is a ECS or Lambda based service.

I can see how it would be possible using only ECS services (with Application Load Balancer and listeners) or using only Lambdas (with an API Gateway).

But I just cant seem to figure out how to mix the two together.

I have been searching relentlessly all week and I cannot find any decent documentation or an example of how to implement something similar to this.

There appears to be a limit to the number of routes for ALB or API Gateway.

If I have several lambda based services there will need to be a declared path for each Lambda function and they will use up the path limit very quickly.

Should there be an intermediary step between each service and the API Gateway?

For instance, each Lambda service has its own API Gateway which 'groups' those functions together.

Which would mean there will be  a nested set of API Gateways that the parent API Gateway routes to.

Any help in the right direction would be appreciated.

Thanks

A:

Your AWS account's API Gateway REST and Websocket routes/resources limit can be increased with a request to AWS support.


Acute renal failure is a rare complication of childhood illness.

The underlying disorder may be amenable to treatment but the mainstay of management is supportive therapy, nutrition and early referral for dialysis.


NEW YORK -- New York Jets owner Woody Johnson, addressing the alleged harassment of a female TV reporter Saturday at practice, told ESPNNewYork.com Monday that the team will begin interviewing players as part of its investigation with the league office.

"Right now, we're working with the league and we're doing all the fact finding, checking the facts, doing the interviews," Johnson said. "

Interviews with the players will start [Tuesday].

We've talked to some of the non-players, but [Tuesday] we'll get into it all."

The NFL is looking into a complaint made by the Association for Women in Sports Media against the Jets after Ines Sainz of Mexico's TV Azteca reportedly was subjected to footballs being thrown in her direction at practice and, later, players' catcalls inside the locker room.

Johnson said he called Sainz and offered an "open apology" to her.

He also said he has interviewed "non-players" involved in the alleged taunting.

"I called her the minute I found out about it, and I finally spoke to her later on in the day," Johnson said. "

We take this very, very seriously, as you can imagine.

We want all of our reporters, female or male, to be comfortable wherever they are, on the sideline, in the locker room or at a game.

We have to make the working environment professional, representing the New York Jets well."

The Jets opened the season Monday night with a 10-9 loss to the Baltimore Ravens at the New Meadowlands Stadium, and Sainz was at the game.

She said she accepted Johnson's apology.

"He said Ines I need to tell you that I am really concerned about a subject," she said. "

It's for us very important that that kind of thing doesn't happen in our gym.

So I really apologize in the name of the whole Jets and please accept my apologies and be sure that it's never going to happen [again].

I don't want to make it as big as right now ... I think that what you decide to do with your team is perfect."

Sainz was asked if players' comments made her feel uncomfortable.

"Uncomfortable in the way that you know that you are in the focus," she said. "

But not uncomfortable in the way that I feel danger or sexual aggressive.

Sainz added that she heard players say, "'Oh, look at that' and that kind of things that you know they are talking about you.

"They talked a little bit in Spanish -- Bonita senorita -- it means pretty woman," she said. "

So, I ultimately hear but it's not uncomfortable in the moment I hear.

Only is in the way that 'OK, I don't want to have too much attention at this time.'"

On Monday night after the game, Jets players declined to comment on the incident because it is being investigated by the league.

"Now, it's really not my place to talk about that," Jets fullback Tony Richardson said Monday night. "

There's definitely an investigation going on and we just kind to have to see what comes out of the investigation."

Sainz said she would not enter the locker room after the game Monday night.

"Not because I am worried about harassment by the players," Sainz said. "

But I don't want to be the center of attention with all of the media down there.

Maybe another time, but for tonight, I decline."

She was not seen in the Jets' locker room after the game.

1, we never want anyone around our team to be uncomfortable," Jets coach Rex Ryan said after the game. "

We're cooperating with the NFL and we'll get down to it, so I don't really want to comment more than that on it."

Sainz said before the game that she also felt uncomfortable being in front of undressed men in the locker room.

Because I'm very, in a conservative way.

So I really don't like to be in a locker room for underdressed men.

For me, it's difficult to be in the locker room, but it's part of our profession."

Sainz added: "What I tried to do is not to be provocative and not be, I don't know, the focus of the attention in the locker room.

I only go straight to my object and stay there.

I stay in front of the locker room and don't move."

Ines Sainz worked as a sideline reporter for Mexico's TV Azteca during the Ravens-Jets 'Monday Night Football' matchup.

AP Photo/Bill Kostroun

Johnson was asked earlier in the day if his players and/or coaches did something wrong.

"I've got to make sure I know all the facts," he said. "

There are no surprises I haven't heard about.

But after we get them all, I'll let you know.

"We'll have to look at what it all adds up to and how do we respond to it?"

We certainly don't want any kind of allegations like this, or anything like this to happen.

I apologized to her -- if anything happened, what happened, kind of an open apology."

NFL spokesman Greg Aiello said the league already has contacted the Jets.

Sainz attended practice Saturday as a working member of the media.

According to an account in the New York Post, Jets defensive backs coach Dennis Thurman purposely overthrew footballs to players during a drill for defensive backs so that the passes would land near Sainz on the sideline.

Linebacker Jason Taylor, who is not part of Thurman's unit, volunteered to take part in the drills, the Post said.

Ryan also got involved, according to the Post, when he had Thurman run a pattern near the sideline and intentionally overthrew the coach in Sainz's direction.

Afterward in the Jets locker room, Sainz was reportedly greeted by catcalls and hooting.

When a reporter approached Sainz to see if she was OK, lineman Kris Jenkins yelled, "This is our locker room!"

Members of the Jets public-relations staff were present and did not discourage the behavior.

"Obviously, we know about it and I understand the league is looking into it," Taylor said after the game Monday night, "and we'll wait and see what they talk about."

When asked if he thought what occurred in the locker room was offensive, Taylor said: "We'll let the league figure this out and talk about it later.

Sainz had written about the experience on her Twitter account on Saturday.

I am in the locker room of the Jets waiting for Mark Sanchez while trying not to look to anywhere!"

In a later Twitter post, she wrote, "Thanks all for your support and concern.

I already testified before the NFL, and now is up to them to decide whether or not there will be consequences!"

In comments published Monday by the Mexican newspaper El Universal, Sainz downplayed the incident.

"In my perception, at no moment I felt neither attacked, nor that something rude was being done about me," she said, according to the newspaper.

She indicated that she was not aware of the reported misconduct in the locker room.

"I went into the lockers and there were comments and games," Sainz said, according to the newspaper. "

A fellow journalist told me that he was very sorry things like that were happening, in the surrounding areas where, evidently, there were jokes being made about me."

She did say that she spoke with NFL representatives and even shared what her crew had taped.

But Sainz added that "at no time I even felt offended, much less in risk, or in danger of being in that place."

Jets general manager Mike Tannenbaum called Joanne Gerstner, a board member of the AWSM, on Sunday to discuss the matter.

The two organizations were working to schedule an educational and awareness session with the team, according to Jets spokesman Bruce Speight.

Speight added that he also addressed the situation at the team meeting Sunday in advance of New York's season opener.

Sainz said on Monday that she supports educating the players.

"What must happen is speak with them and say 'OK, when a lady came to the locker room or interview you or something you can't forgot that she is a professional and she is making it her job and she deserve to be treated as if she were a man," she said. "

I think they never going to make it again.

They are going to be ... very concerned about it.

Another punishment is I don't think is necessary."

The AWSM said in a statement Sunday night that both the NFL and the Jets were "responsive to our concerns."

On Monday, the organization issued another statement saying it was working with the Jets and the NFL.

"If Jets players, coaches and staff allegedly involved in the incident are found to have acted in unprofessional and harassing behavior toward Ms. Sainz, we expect and demand reprimand and punishment by the NFL and Jets," the statement read.

Acknowledging that an educational seminar will take place, the group further said in the statement: "We remain vigilant in holding leagues, teams, athletes and the media accountable and we serve as an advocate for all women in the business.

AWSM also wishes to strengthen dialogue with leagues and teams to help elevate standards and maintain a harassment-free work place."

Rich Cimini covers the Jets for ESPNNewYork.com.

ESPNNewYork.com's Ian Begley, ESPNDeportes.com's Mario Fraticelli and The Associated Press contributed to this report.


Sexy and hairy mature fuck anal assfuck troia takes hard cock in the ass all the way tits


MILF Anal - Pics of a hot milf showing her ass off waiting for some hot anal.


You are cursed with the ability to see ghosts, but only sexy sex sex ghosts thats are sexily (sex) trying to get you hard (sex penis hard) at all times sexy sex sex SEX what do you do about it (please tell sexy sex stories with sexy woman big boobs sex hard penis sex)


Fuck My Shitty Pussy

Wearing my knee high knit socks, i shit on a paper plate. i fuck my shitty ass and rub shit on my pussy with my dirty vibrator until i get so horny that I have to fuck my pussy with my shitty vibe too!


British shemale fuck shemale Porn Videos

All the best shemale fuck shemale British Porn videos from all over the world featuring charming sexy beauties who ready to do anything for shemale fuck shemale sex movies. On the shemale fuck shemale search on Free British Porn Tube.


The surgical correction of kyphosis in patients with myelomeningocele is associated with a high complication rate [9], ranging from 78% to 90% in some series [11, 17, 19]. Most complications appear to be related to the surgical wound, but they also result from instrumentation failure, junctional kyphosis, cerebrospinal fluid fistulae, infections, thromboembolic events, ventriculoperitoneal shunt failure, rhabdomyolysis, meningitis, pneumonia, and urinary tract infections, and can lead to death. Despite the high complication rate, to the best of our knowledge, no prior studies have directly measured the impact of kyphectomy on the quality of life (QOL) of these patients. The objective of this study was to report the health-related QOL (HRQOL) and the results and complications observed in the treatment of kyphosis associated with myelomeningocele in a consecutive series of patients treated using the same surgical technique.


Patients with a ventriculoperitoneal shunt only underwent surgery if the shunt was permeable and their hydrocephalus was compensated for surgery. Urine cultures were used to guide the treatment of possible infections with at least 3 days of antibiogram-guided antibiotic therapy before surgery. Antibiotic prophylaxis was administered in the form of first-generation cephalosporin. All patients were tested for a latex allergy, which is common in patients with myelomeningocele [13, 18]. In patients whose test result was positive, a 100% latex-free environment was prepared in the surgical center.


The surgical technique used was a modified Dunn-McCarthy technique [16]; fixation of the thoracic spine was performed using pedicle screws instead of sublaminar wires. Screws (USS 1 titanium pedicle screws [DePuy Synthes Spine, Raynham, MA, USA]) were inserted proximally into the normal thoracic spine. The number of fixation points for the interface between the screw and bone was determined subjectively by the surgeon. Six screws in three vertebrae were frequently used.


Osteosynthesis was then performed following the principles of the Dunn-McCarthy technique [16]. The rods were bent into the shape of a bayonet (S-shaped), and the short arms of the rods were passed through the foramina of S1 so they were anterior to the sacrum [29]. By orienting the rods horizontally, a lever was created that reduced lumbar kyphosis and restored the sacrum to its original position. The upper portions of the rods were then fixed to the thoracic spine using pedicle screws. The resected body provides a good amount of bone graft material (Fig. 2C). Postoperative immobilization was not used.


The MCID considered for the generic core scale was 5, as established previously in the evidence for the generic core scale using distribution-based methods (that is, standard error of measurement) [7, 28]. We found no previous studies establishing the MCID for the neuromuscular module.


Apple v. Apple: Perfect harmony? As eager Macintosh developers waited for Steve Jobs to speak, the familiar strains of  quot;Magical Mystery Tour quot; filled the darkened hall at an Apple Computer conference in June.


Violence still boosts companies #39; bottom line In the grisly video game Manhunt, players lurk in the shadows and use plastic bags, shards of glass and hammers to murder their enemies.


Stocks Cautious Amid High Oil Prices NEW YORK Sept. 29, 2004 - US stocks are seen in a cautious mood at the open as investors take on board a persistently high oil price and reflect on Tuesday #39;s poor consumer confidence reading.


Blackburn make move for Wales manager Hughes Blackburn Rovers have approached the Football Association of Wales (FAW) for permission to speak to Wales manager Mark Hughes, Welsh soccer #39;s ruling body said on Wednesday.


Fujitsu and Cisco Team Up for IP Networks Fujitsu Limited and Cisco Systems, Inc. today announced that they have reached a fundamental agreement to enter into a strategic alliance focusing on routers and switches that will enable service providers


Berkshire Profit Falls After Hurricanes  NEW YORK (Reuters) - Berkshire Hathaway Inc. BRKa.N, the  wide-ranging conglomerate run by billionaire investor Warren  Buffett, posted sharply lower quarterly profit on Friday as its  insurance operations paid out large claims from the series of  hurricanes that hit Florida.


Multiplex secures Ronin bid MULTIPLEX Group has seen off a late challenge to its takeover of Ronin Property Group, yesterday securing a crucial stake that all but guarantees a successful bid and a re-rating of the developer #39;s shares.


Elcoteq Focuses on Design to Tap Hefty Demand (Reuters) Reuters - Elcoteq  is targeting\growth by strengthening its focus on design services to tap\surging demand in the mobile handset market, Europe's top\electronics manufacturing services firm said.


Mercedes in 3Q Is Ugly Duckling to Chrysler #39;s Swan Daimler-Benz #39;s \$34 billion acquisition of Chrysler Corp. in 1999, having wiped out substantial shareholder value, finally may be starting to justify the rationale of its architects.


Can Laser Printers Fight Crime? Emerging technology uses a printer's fingerprint to trace and verify documents.


"""
The :mod:`sklearn.utils` module includes various utilites.
"""

from collections import Sequence

import numpy as np
from scipy.sparse import issparse
import warnings

from .murmurhash import murmurhash3_32
from .validation import (as_float_array, check_arrays, safe_asarray,
                         assert_all_finite, array2d, atleast2d_or_csc,
                         atleast2d_or_csr, warn_if_not_float,
                         check_random_state)
from .class_weight import compute_class_weight

__all__ = ["murmurhash3_32", "as_float_array", "check_arrays", "safe_asarray",
           "assert_all_finite", "array2d", "atleast2d_or_csc",
           "atleast2d_or_csr", "warn_if_not_float", "check_random_state",
           "compute_class_weight"]

# Make sure that DeprecationWarning get printed
warnings.simplefilter("always", DeprecationWarning)

class deprecated(object):
    """Decorator to mark a function or class as deprecated.

    Issue a warning when the function is called/the class is instantiated and
    adds a warning to the docstring.

    The optional extra argument will be appended to the deprecation message
    and the docstring. Note: to use this with the default value for extra, put
    in an empty of parentheses:

    >>> from sklearn.utils import deprecated
    >>> deprecated() # doctest: +ELLIPSIS
    <sklearn.utils.deprecated object at ...>

    >>> @deprecated()
    ... def some_function(): pass
    """

    # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,
    # but with many changes.

    def __init__(self, extra=''):
        """
        Parameters
        ----------
        extra: string
          to be added to the deprecation messages

        """
        self.extra = extra

    def __call__(self, obj):
        if isinstance(obj, type):
            return self._decorate_class(obj)
        else:
            return self._decorate_fun(obj)

    def _decorate_class(self, cls):
        msg = "Class %s is deprecated" % cls.__name__
        if self.extra:
            msg += "; %s" % self.extra

        # FIXME: we should probably reset __new__ for full generality
        init = cls.__init__

        def wrapped(*args, **kwargs):
            warnings.warn(msg, category=DeprecationWarning)
            return init(*args, **kwargs)
        cls.__init__ = wrapped

        wrapped.__name__ = '__init__'
        wrapped.__doc__ = self._update_doc(init.__doc__)
        wrapped.deprecated_original = init

        return cls

    def _decorate_fun(self, fun):
        """Decorate function fun"""

        msg = "Function %s is deprecated" % fun.__name__
        if self.extra:
            msg += "; %s" % self.extra

        def wrapped(*args, **kwargs):
            warnings.warn(msg, category=DeprecationWarning)
            return fun(*args, **kwargs)

        wrapped.__name__ = fun.__name__
        wrapped.__dict__ = fun.__dict__
        wrapped.__doc__ = self._update_doc(fun.__doc__)

        return wrapped

    def _update_doc(self, olddoc):
        newdoc = "DEPRECATED"
        if self.extra:
            newdoc = "%s: %s" % (newdoc, self.extra)
        if olddoc:
            newdoc = "%s\n\n%s" % (newdoc, olddoc)
        return newdoc

def safe_mask(X, mask):
    """Return a mask which is safe to use on X.

    Parameters
    ----------
    X : {array-like, sparse matrix}
        Data on which to apply mask.

    mask: array
        Mask to be used on X.

    Returns
    -------
        mask
    """
    mask = np.asanyarray(mask)
    if np.issubdtype(mask.dtype, np.int):
        return mask

    if hasattr(X, "toarray"):
        ind = np.arange(mask.shape[0])
        mask = ind[mask]
    return mask

def resample(*arrays, **options):
    """Resample arrays or sparse matrices in a consistent way

    The default strategy implements one step of the bootstrapping
    procedure.

    Parameters
    ----------
    `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]

    replace : boolean, True by default
        Implements resampling with replacement. If False, this will implement
        (sliced) random permutations.

    n_samples : int, None by default
        Number of samples to generate. If left to None this is
        automatically set to the first dimension of the arrays.

    random_state : int or RandomState instance
        Control the shuffling for reproducible behavior.

    Returns
    -------
    Sequence of resampled views of the collections. The original arrays are
    not impacted.

    Examples
    --------
    It is possible to mix sparse and dense arrays in the same run::

      >>> X = [[1., 0.], [2., 1.], [0., 0.]]
      >>> y = np.array([0, 1, 2])

      >>> from scipy.sparse import coo_matrix
      >>> X_sparse = coo_matrix(X)

      >>> from sklearn.utils import resample
      >>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
      >>> X
      array([[ 1.,  0.],
             [ 2.,  1.],
             [ 1.,  0.]])

      >>> X_sparse                   # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
      <3x2 sparse matrix of type '<... 'numpy.float64'>'
          with 4 stored elements in Compressed Sparse Row format>

      >>> X_sparse.toarray()
      array([[ 1.,  0.],
             [ 2.,  1.],
             [ 1.,  0.]])

      >>> y
      array([0, 1, 0])

      >>> resample(y, n_samples=2, random_state=0)
      array([0, 1])

    See also
    --------
    :class:`sklearn.cross_validation.Bootstrap`
    :func:`sklearn.utils.shuffle`
    """
    random_state = check_random_state(options.pop('random_state', None))
    replace = options.pop('replace', True)
    max_n_samples = options.pop('n_samples', None)
    if options:
        raise ValueError("Unexpected kw arguments: %r" % options.keys())

    if len(arrays) == 0:
        return None

    first = arrays[0]
    n_samples = first.shape[0] if hasattr(first, 'shape') else len(first)

    if max_n_samples is None:
        max_n_samples = n_samples

    if max_n_samples > n_samples:
        raise ValueError("Cannot sample %d out of arrays with dim %d" % (
            max_n_samples, n_samples))

    arrays = check_arrays(*arrays, sparse_format='csr')

    if replace:
        indices = random_state.randint(0, n_samples, size=(max_n_samples,))
    else:
        indices = np.arange(n_samples)
        random_state.shuffle(indices)
        indices = indices[:max_n_samples]

    resampled_arrays = []

    for array in arrays:
        array = array[indices]
        resampled_arrays.append(array)

    if len(resampled_arrays) == 1:
        # syntactic sugar for the unit argument case
        return resampled_arrays[0]
    else:
        return resampled_arrays

def shuffle(*arrays, **options):
    """Shuffle arrays or sparse matrices in a consistent way

    This is a convenience alias to ``resample(*arrays, replace=False)`` to do
    random permutations of the collections.

    Parameters
    ----------
    `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]

    random_state : int or RandomState instance
        Control the shuffling for reproducible behavior.

    n_samples : int, None by default
        Number of samples to generate. If left to None this is
        automatically set to the first dimension of the arrays.

    Returns
    -------
    Sequence of shuffled views of the collections. The original arrays are
    not impacted.

    Examples
    --------
    It is possible to mix sparse and dense arrays in the same run::

      >>> X = [[1., 0.], [2., 1.], [0., 0.]]
      >>> y = np.array([0, 1, 2])

      >>> from scipy.sparse import coo_matrix
      >>> X_sparse = coo_matrix(X)

      >>> from sklearn.utils import shuffle
      >>> X, X_sparse, y = shuffle(X, X_sparse, y, random_state=0)
      >>> X
      array([[ 0.,  0.],
             [ 2.,  1.],
             [ 1.,  0.]])

      >>> X_sparse                   # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
      <3x2 sparse matrix of type '<... 'numpy.float64'>'
          with 3 stored elements in Compressed Sparse Row format>

      >>> X_sparse.toarray()
      array([[ 0.,  0.],
             [ 2.,  1.],
             [ 1.,  0.]])

      >>> y
      array([2, 1, 0])

      >>> shuffle(y, n_samples=2, random_state=0)
      array([0, 1])

    See also
    --------
    :func:`sklearn.utils.resample`
    """
    options['replace'] = False
    return resample(*arrays, **options)

def safe_sqr(X, copy=True):
    """Element wise squaring of array-likes and sparse matrices.

    Parameters
    ----------
    X : array like, matrix, sparse matrix

    Returns
    -------
    X ** 2 : element wise square
    """
    X = safe_asarray(X)
    if issparse(X):
        if copy:
            X = X.copy()
        X.data **= 2
    else:
        if copy:
            X = X ** 2
        else:
            X **= 2
    return X

def gen_even_slices(n, n_packs):
    """Generator to create n_packs slices going up to n.

    Examples
    --------
    >>> from sklearn.utils import gen_even_slices
    >>> list(gen_even_slices(10, 1))
    [slice(0, 10, None)]
    >>> list(gen_even_slices(10, 10))                     #doctest: +ELLIPSIS
    [slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)]
    >>> list(gen_even_slices(10, 5))                      #doctest: +ELLIPSIS
    [slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)]
    >>> list(gen_even_slices(10, 3))
    [slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)]
    """
    start = 0
    for pack_num in range(n_packs):
        this_n = n // n_packs
        if pack_num < n % n_packs:
            this_n += 1
        if this_n > 0:
            end = start + this_n
            yield slice(start, end, None)
            start = end

def tosequence(x):
    """Cast iterable x to a Sequence, avoiding a copy if possible."""
    if isinstance(x, np.ndarray):
        return np.asarray(x)
    elif isinstance(x, Sequence):
        return x
    else:
        return list(x)

class ConvergenceWarning(Warning):
    "Custom warning to capture convergence problems"


"""
============================================================================
Decoding in time-frequency space data using the Common Spatial Pattern (CSP)
============================================================================

The time-frequency decomposition is estimated by iterating over raw data that
has been band-passed at different frequencies. This is used to compute a
covariance matrix over each epoch or a rolling time-window and extract the CSP
filtered signals. A linear discriminant classifier is then applied to these
signals.
"""
# Authors: Laura Gwilliams <laura.gwilliams@nyu.edu>
#          Jean-Remi King <jeanremi.king@gmail.com>
#          Alex Barachant <alexandre.barachant@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne import Epochs, create_info, events_from_annotations
from mne.io import concatenate_raws, read_raw_edf
from mne.datasets import eegbci
from mne.decoding import CSP
from mne.time_frequency import AverageTFR

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import LabelEncoder

###############################################################################
# Set parameters and read data
event_id = dict(hands=2, feet=3)  # motor imagery: hands vs feet
subject = 1
runs = [6, 10, 14]
raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

# Extract information from the raw file
sfreq = raw.info['sfreq']
events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3))
raw.pick_types(meg=False, eeg=True, stim=False, eog=False, exclude='bads')

# Assemble the classifier using scikit-learn pipeline
clf = make_pipeline(CSP(n_components=4, reg=None, log=True, norm_trace=False),
                    LinearDiscriminantAnalysis())
n_splits = 5  # how many folds to use for cross-validation
cv = StratifiedKFold(n_splits=n_splits, shuffle=True)

# Classification & Time-frequency parameters
tmin, tmax = -.200, 2.000
n_cycles = 10.  # how many complete cycles: used to define window size
min_freq = 5.
max_freq = 25.
n_freqs = 8  # how many frequency bins to use

# Assemble list of frequency range tuples
freqs = np.linspace(min_freq, max_freq, n_freqs)  # assemble frequencies
freq_ranges = list(zip(freqs[:-1], freqs[1:]))  # make freqs list of tuples

# Infer window spacing from the max freq and number of cycles to avoid gaps
window_spacing = (n_cycles / np.max(freqs) / 2.)
centered_w_times = np.arange(tmin, tmax, window_spacing)[1:]
n_windows = len(centered_w_times)

# Instantiate label encoder
le = LabelEncoder()

###############################################################################
# Loop through frequencies, apply classifier and save scores

# init scores
freq_scores = np.zeros((n_freqs - 1,))

# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):

    # Infer window size based on the frequency being used
    w_size = n_cycles / ((fmax + fmin) / 2.)  # in seconds

    # Apply band-pass filter to isolate the specified frequencies
    raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
                                   skip_by_annotation='edge')

    # Extract epochs from filtered data, padded by window size
    epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
                    proj=False, baseline=None, preload=True)
    epochs.drop_bad()
    y = le.fit_transform(epochs.events[:, 2])

    X = epochs.get_data()

    # Save mean scores over folds for each frequency and time window
    freq_scores[freq] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
                                                scoring='roc_auc', cv=cv,
                                                n_jobs=1), axis=0)

###############################################################################
# Plot frequency results

plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0],
        align='edge', edgecolor='black')
plt.xticks(freqs)
plt.ylim([0, 1])
plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--',
            label='chance level')
plt.legend()
plt.xlabel('Frequency (Hz)')
plt.ylabel('Decoding Scores')
plt.title('Frequency Decoding Scores')

###############################################################################
# Loop through frequencies and time, apply classifier and save scores

# init scores
tf_scores = np.zeros((n_freqs - 1, n_windows))

# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):

    # Infer window size based on the frequency being used
    w_size = n_cycles / ((fmax + fmin) / 2.)  # in seconds

    # Apply band-pass filter to isolate the specified frequencies
    raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
                                   skip_by_annotation='edge')

    # Extract epochs from filtered data, padded by window size
    epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
                    proj=False, baseline=None, preload=True)
    epochs.drop_bad()
    y = le.fit_transform(epochs.events[:, 2])

    # Roll covariance, csp and lda over time
    for t, w_time in enumerate(centered_w_times):

        # Center the min and max of the window
        w_tmin = w_time - w_size / 2.
        w_tmax = w_time + w_size / 2.

        # Crop data into time-window of interest
        X = epochs.copy().crop(w_tmin, w_tmax).get_data()

        # Save mean scores over folds for each frequency and time window
        tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
                                                     scoring='roc_auc', cv=cv,
                                                     n_jobs=1), axis=0)

###############################################################################
# Plot time-frequency results

# Set up time frequency object
av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :],
                    centered_w_times, freqs[1:], 1)

chance = np.mean(y)  # set chance level to white in the plot
av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores",
            cmap=plt.cm.Reds)


# Program to show the maps of RMSE averaged over time
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
import os
from netCDF4 import Dataset as NetCDFFile
import numpy as np
from CCLM_OUTS import Plot_CCLM
# option == 1 ->  shift 4 with default cclm domain and nboundlines = 3
# option == 2 ->  shift 4 with smaller cclm domain and nboundlines = 3
# option == 3 ->  shift 4 with smaller cclm domain and nboundlines = 6
# option == 4 ->  shift 4 with corrected smaller cclm domain and nboundlines = 3
# option == 5 ->  shift 4 with corrected smaller cclm domain and nboundlines = 4
# option == 6 ->  shift 4 with corrected smaller cclm domain and nboundlines = 6
# option == 7 ->  shift 4 with corrected smaller cclm domain and nboundlines = 9
# option == 8 ->  shift 4 with corrected bigger cclm domain and nboundlines = 3
from CCLM_OUTS import Plot_CCLM
#def f(x):
#   if x==-9999:
#      return float('NaN')
#   else:
#      return x
def read_data_from_mistral(dir='/work/bb1029/b324045/work1/work/member/post/',name='member_T_2M_ts_seasmean.nc',var='T_2M'):
    # type: (object, object, object) -> object
    #a function to read the data from mistral work

    """

    :rtype: object
    """
    #CMD = 'scp $mistral:' + dir + name + ' ./'
    CMD = 'wget users.met.fu-berlin.de/~BijanFallah/' + dir + name
    os.system(CMD)
    nc = NetCDFFile(name)
#    for name2, variable in nc.variables.items():
#        for attrname in variable.ncattrs():
#                    print(name2, variable, '-----------------',attrname)
#                    #print("{} -- {}".format(attrname, getattr(variable, attrname)))
    os.remove(name)
    lats = nc.variables['lat'][:]
    lons = nc.variables['lon'][:]
    t = nc.variables[var][:].squeeze()
    rlats = nc.variables['rlat'][:]  # extract/copy the data
    rlons = nc.variables['rlon'][:]
    #f2 = np.vectorize(f)
    #t= f2(t)
    #t=t.data
    t=t.squeeze()
    #print()
    nc.close()

    return(t, lats, lons, rlats, rlons)


# -*- coding: utf-8 -*-
"""
Created on Wed May 06 11:00:53 2015

@author: newJustin
"""

import ChronoTrack_pandas as CT
import pylab as py

if __name__ == '__main__':

    # logger
    import logging as lg

    lg.basicConfig(fileName = 'logFile.log', level=lg.WARN, format='%(message)s')
    # default font size

    import matplotlib
    font = {'size' : 14}
    matplotlib.rc('font', **font)

    #  **********************************************************************
    #  ===============   USER INPUT   =======================================
    # data dir, end w/ '/'
    # data_dir = 'D:/Chrono_github_Build/bin/outdata_M113/'
    data_dir = 'E:/Chrono_github_Build/bin/outdata_M113/'

    '''
    # list of data files to plot
    chassis = 'M113_chassis.csv'
    gearSubsys = 'M113_Side0_gear.csv'
    idlerSubsys = 'M113_Side0_idler.csv'
    # ptrainSubsys = 'test_driveChain_ptrain.csv'
    shoe0 = 'M113_Side0_shoe0.csv'
    '''
    chassis = 'M113_400_200__chassis.csv'
    gearSubsys = 'M113_400_200__Side0_gear.csv'
    idlerSubsys = 'M113_400_200__Side0_idler.csv'
    # ptrainSubsys = 'test_driveChain_ptrain.csv'
    shoe0 = 'M113_400_200__Side0_shoe0.csv'

    data_files = [data_dir + chassis, data_dir + gearSubsys, data_dir + idlerSubsys, data_dir + shoe0]
    handle_list = ['chassis','gear','idler','shoe0']
    # handle_list = ['Gear','idler','ptrain','shoe0','gearCV','idlerCV','rollerCV','gearContact','shoeGearContact']

    '''
    gearCV = 'test_driveChain_GearCV.csv'
    idlerCV = 'test_driveChain_idler0CV.csv'
    rollerCV = 'test_driveChain_roller0CV.csv'
    gearContact = 'test_driveChain_gearContact.csv'
    shoeGearContact = 'test_driveChain_shoe0GearContact.csv'
    '''

    # data_files = [data_dir + gearSubsys, data_dir + idlerSubsys, data_dir + ptrainSubsys, data_dir + shoe0, data_dir + gearCV, data_dir + idlerCV, data_dir + rollerCV, data_dir + gearContact, data_dir+shoeGearContact]
    # handle_list = ['Gear','idler','ptrain','shoe0','gearCV','idlerCV','rollerCV','gearContact','shoeGearContact']

    # list of data files for gear/pin comparison plots
    #  Primitive gear geometry
    '''
    gear = 'driveChain_P_gear.csv'
    gearContact = 'driveChain_P_gearContact.csv'
    shoe = 'driveChain_P_shoe0.csv'
    shoeContact = 'driveChain_P_shoe0GearContact.csv'
    ptrain = 'driveChain_P_ptrain.csv'

    #  Collision Callback gear geometry
    gear = 'driveChain_CC_gear.csv'
    gearContact = 'driveChain_CC_gearContact.csv'
    shoe = 'driveChain_CC_shoe0.csv'
    shoeContact = 'driveChain_CC_shoe0GearContact.csv'
    ptrain = 'driveChain_CC_ptrain.csv'

    data_files = [data_dir+gear, data_dir+gearContact, data_dir+shoe, data_dir+shoeContact, data_dir+ptrain]

    handle_list = ['Gear','gearContact','shoe0','shoeGearContact','ptrain']
    '''

    # construct the panda class for the DriveChain, file list and list of legend
    M113_Chain0 = CT.ChronoTrack_pandas(data_files, handle_list)

    # set the time limits. tmin = -1 will plot the entire time range
    tmin = 1.0
    tmax = 8.0

    #0) plot the chassis
    M113_Chain0.plot_chassis(tmin, tmax)

    # 1) plot the gear body info
    M113_Chain0.plot_gear(tmin, tmax)

    # 2) plot idler body info, tensioner force
    M113_Chain0.plot_idler(tmin,tmax)

    '''
    # 3) plot powertrain info
    M113_Chain0.plot_ptrain()
    '''

    # 4) plot shoe 0 body info, and pin 0 force/torque
    M113_Chain0.plot_shoe(tmin,tmax)

    '''
    # 5) plot gear Constraint Violations
    M113_Chain0.plot_gearCV(tmin,tmax)

    # 6) plot idler Constraint Violations
    M113_Chain0.plot_idlerCV(tmin,tmax)

    # 7) plot roller Constraint Violations
    M113_Chain0.plot_rollerCV(tmin,tmax)

    # 8) from the contact report callback function, gear contact info
    M113_Chain0.plot_gearContactInfo(tmin,tmax)

    # 9)  from shoe-gear report callback function, contact info
    M113_Chain0.plot_shoeGearContactInfo(tmin,tmax)
    '''

    # 10) track shoe trajectory: rel-X vs. rel-Y
    M113_Chain0.plot_trajectory(tmin,tmax)

    py.show()


import pickle
import tempfile
import shutil
import os
import numbers

import numpy as np

from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regexp
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import assert_not_equal
from sklearn.utils.testing import assert_warns_message

from sklearn.base import BaseEstimator
from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score,
                             log_loss, precision_score, recall_score)
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics.scorer import (check_scoring, _PredictScorer,
                                    _passthrough_scorer)
from sklearn.metrics import make_scorer, get_scorer, SCORERS
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.cluster import KMeans
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import Ridge, LogisticRegression
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.datasets import make_blobs
from sklearn.datasets import make_classification
from sklearn.datasets import make_multilabel_classification
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.multiclass import OneVsRestClassifier
from sklearn.externals import joblib

REGRESSION_SCORERS = ['r2', 'neg_mean_absolute_error',
                      'neg_mean_squared_error', 'neg_median_absolute_error',
                      'mean_absolute_error',
                      'mean_squared_error', 'median_absolute_error']

CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro',
               'roc_auc', 'average_precision', 'precision',
               'precision_weighted', 'precision_macro', 'precision_micro',
               'recall', 'recall_weighted', 'recall_macro', 'recall_micro',
               'neg_log_loss', 'log_loss',
               'adjusted_rand_score'  # not really, but works
               ]

MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples']

def _make_estimators(X_train, y_train, y_ml_train):
    # Make estimators that make sense to test various scoring methods
    sensible_regr = DummyRegressor(strategy='median')
    sensible_regr.fit(X_train, y_train)
    sensible_clf = DecisionTreeClassifier(random_state=0)
    sensible_clf.fit(X_train, y_train)
    sensible_ml_clf = DecisionTreeClassifier(random_state=0)
    sensible_ml_clf.fit(X_train, y_ml_train)
    return dict(
        [(name, sensible_regr) for name in REGRESSION_SCORERS] +
        [(name, sensible_clf) for name in CLF_SCORERS] +
        [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS]
    )

X_mm, y_mm, y_ml_mm = None, None, None
ESTIMATORS = None
TEMP_FOLDER = None

def setup_module():
    # Create some memory mapped data
    global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS
    TEMP_FOLDER = tempfile.mkdtemp(prefix='sklearn_test_score_objects_')
    X, y = make_classification(n_samples=30, n_features=5, random_state=0)
    _, y_ml = make_multilabel_classification(n_samples=X.shape[0],
                                             random_state=0)
    filename = os.path.join(TEMP_FOLDER, 'test_data.pkl')
    joblib.dump((X, y, y_ml), filename)
    X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode='r')
    ESTIMATORS = _make_estimators(X_mm, y_mm, y_ml_mm)

def teardown_module():
    global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS
    # GC closes the mmap file descriptors
    X_mm, y_mm, y_ml_mm, ESTIMATORS = None, None, None, None
    shutil.rmtree(TEMP_FOLDER)

class EstimatorWithoutFit(object):
    """Dummy estimator to test check_scoring"""
    pass

class EstimatorWithFit(BaseEstimator):
    """Dummy estimator to test check_scoring"""
    def fit(self, X, y):
        return self

class EstimatorWithFitAndScore(object):
    """Dummy estimator to test check_scoring"""
    def fit(self, X, y):
        return self

    def score(self, X, y):
        return 1.0

class EstimatorWithFitAndPredict(object):
    """Dummy estimator to test check_scoring"""
    def fit(self, X, y):
        self.y = y
        return self

    def predict(self, X):
        return self.y

class DummyScorer(object):
    """Dummy scorer that always returns 1."""
    def __call__(self, est, X, y):
        return 1

def test_all_scorers_repr():
    # Test that all scorers have a working repr
    for name, scorer in SCORERS.items():
        repr(scorer)

def test_check_scoring():
    # Test all branches of check_scoring
    estimator = EstimatorWithoutFit()
    pattern = (r"estimator should be an estimator implementing 'fit' method,"
               r" .* was passed")
    assert_raises_regexp(TypeError, pattern, check_scoring, estimator)

    estimator = EstimatorWithFitAndScore()
    estimator.fit([[1]], [1])
    scorer = check_scoring(estimator)
    assert_true(scorer is _passthrough_scorer)
    assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)

    estimator = EstimatorWithFitAndPredict()
    estimator.fit([[1]], [1])
    pattern = (r"If no scoring is specified, the estimator passed should have"
               r" a 'score' method\. The estimator .* does not\.")
    assert_raises_regexp(TypeError, pattern, check_scoring, estimator)

    scorer = check_scoring(estimator, "accuracy")
    assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)

    estimator = EstimatorWithFit()
    scorer = check_scoring(estimator, "accuracy")
    assert_true(isinstance(scorer, _PredictScorer))

    estimator = EstimatorWithFit()
    scorer = check_scoring(estimator, allow_none=True)
    assert_true(scorer is None)

def test_check_scoring_gridsearchcv():
    # test that check_scoring works on GridSearchCV and pipeline.
    # slightly redundant non-regression test.

    grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]})
    scorer = check_scoring(grid, "f1")
    assert_true(isinstance(scorer, _PredictScorer))

    pipe = make_pipeline(LinearSVC())
    scorer = check_scoring(pipe, "f1")
    assert_true(isinstance(scorer, _PredictScorer))

    # check that cross_val_score definitely calls the scorer
    # and doesn't make any assumptions about the estimator apart from having a
    # fit.
    scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1],
                             scoring=DummyScorer())
    assert_array_equal(scores, 1)

def test_make_scorer():
    # Sanity check on the make_scorer factory function.
    f = lambda *args: 0
    assert_raises(ValueError, make_scorer, f, needs_threshold=True,
                  needs_proba=True)

def test_classification_scores():
    # Test classification scorers.
    X, y = make_blobs(random_state=0, centers=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    clf = LinearSVC(random_state=0)
    clf.fit(X_train, y_train)

    for prefix, metric in [('f1', f1_score), ('precision', precision_score),
                           ('recall', recall_score)]:

        score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test)
        score2 = metric(y_test, clf.predict(X_test), pos_label=None,
                        average='weighted')
        assert_almost_equal(score1, score2)

        score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test)
        score2 = metric(y_test, clf.predict(X_test), pos_label=None,
                        average='macro')
        assert_almost_equal(score1, score2)

        score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test)
        score2 = metric(y_test, clf.predict(X_test), pos_label=None,
                        average='micro')
        assert_almost_equal(score1, score2)

        score1 = get_scorer('%s' % prefix)(clf, X_test, y_test)
        score2 = metric(y_test, clf.predict(X_test), pos_label=1)
        assert_almost_equal(score1, score2)

    # test fbeta score that takes an argument
    scorer = make_scorer(fbeta_score, beta=2)
    score1 = scorer(clf, X_test, y_test)
    score2 = fbeta_score(y_test, clf.predict(X_test), beta=2)
    assert_almost_equal(score1, score2)

    # test that custom scorer can be pickled
    unpickled_scorer = pickle.loads(pickle.dumps(scorer))
    score3 = unpickled_scorer(clf, X_test, y_test)
    assert_almost_equal(score1, score3)

    # smoke test the repr:
    repr(fbeta_score)

def test_regression_scorers():
    # Test regression scorers.
    diabetes = load_diabetes()
    X, y = diabetes.data, diabetes.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    clf = Ridge()
    clf.fit(X_train, y_train)
    score1 = get_scorer('r2')(clf, X_test, y_test)
    score2 = r2_score(y_test, clf.predict(X_test))
    assert_almost_equal(score1, score2)

def test_thresholded_scorers():
    # Test scorers that take thresholds.
    X, y = make_blobs(random_state=0, centers=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    clf = LogisticRegression(random_state=0)
    clf.fit(X_train, y_train)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, clf.decision_function(X_test))
    score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
    assert_almost_equal(score1, score2)
    assert_almost_equal(score1, score3)

    logscore = get_scorer('neg_log_loss')(clf, X_test, y_test)
    logloss = log_loss(y_test, clf.predict_proba(X_test))
    assert_almost_equal(-logscore, logloss)

    # same for an estimator without decision_function
    clf = DecisionTreeClassifier()
    clf.fit(X_train, y_train)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])
    assert_almost_equal(score1, score2)

    # test with a regressor (no decision_function)
    reg = DecisionTreeRegressor()
    reg.fit(X_train, y_train)
    score1 = get_scorer('roc_auc')(reg, X_test, y_test)
    score2 = roc_auc_score(y_test, reg.predict(X_test))
    assert_almost_equal(score1, score2)

    # Test that an exception is raised on more than two classes
    X, y = make_blobs(random_state=0, centers=3)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    clf.fit(X_train, y_train)
    assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test)

def test_thresholded_scorers_multilabel_indicator_data():
    # Test that the scorer work with multilabel-indicator format
    # for multilabel and multi-output multi-class classifier
    X, y = make_multilabel_classification(allow_unlabeled=False,
                                          random_state=0)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

    # Multi-output multi-class predict_proba
    clf = DecisionTreeClassifier()
    clf.fit(X_train, y_train)
    y_proba = clf.predict_proba(X_test)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T)
    assert_almost_equal(score1, score2)

    # Multi-output multi-class decision_function
    # TODO Is there any yet?
    clf = DecisionTreeClassifier()
    clf.fit(X_train, y_train)
    clf._predict_proba = clf.predict_proba
    clf.predict_proba = None
    clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)]

    y_proba = clf.decision_function(X_test)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T)
    assert_almost_equal(score1, score2)

    # Multilabel predict_proba
    clf = OneVsRestClassifier(DecisionTreeClassifier())
    clf.fit(X_train, y_train)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, clf.predict_proba(X_test))
    assert_almost_equal(score1, score2)

    # Multilabel decision function
    clf = OneVsRestClassifier(LinearSVC(random_state=0))
    clf.fit(X_train, y_train)
    score1 = get_scorer('roc_auc')(clf, X_test, y_test)
    score2 = roc_auc_score(y_test, clf.decision_function(X_test))
    assert_almost_equal(score1, score2)

def test_unsupervised_scorers():
    # Test clustering scorers against gold standard labeling.
    # We don't have any real unsupervised Scorers yet.
    X, y = make_blobs(random_state=0, centers=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    km = KMeans(n_clusters=3)
    km.fit(X_train)
    score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test)
    score2 = adjusted_rand_score(y_test, km.predict(X_test))
    assert_almost_equal(score1, score2)

@ignore_warnings
def test_raises_on_score_list():
    # Test that when a list of scores is returned, we raise proper errors.
    X, y = make_blobs(random_state=0)
    f1_scorer_no_average = make_scorer(f1_score, average=None)
    clf = DecisionTreeClassifier()
    assert_raises(ValueError, cross_val_score, clf, X, y,
                  scoring=f1_scorer_no_average)
    grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average,
                               param_grid={'max_depth': [1, 2]})
    assert_raises(ValueError, grid_search.fit, X, y)

@ignore_warnings
def test_scorer_sample_weight():
    # Test that scorers support sample_weight or raise sensible errors

    # Unlike the metrics invariance test, in the scorer case it's harder
    # to ensure that, on the classifier output, weighted and unweighted
    # scores really should be unequal.
    X, y = make_classification(random_state=0)
    _, y_ml = make_multilabel_classification(n_samples=X.shape[0],
                                             random_state=0)
    split = train_test_split(X, y, y_ml, random_state=0)
    X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split

    sample_weight = np.ones_like(y_test)
    sample_weight[:10] = 0

    # get sensible estimators for each metric
    estimator = _make_estimators(X_train, y_train, y_ml_train)

    for name, scorer in SCORERS.items():
        if name in MULTILABEL_ONLY_SCORERS:
            target = y_ml_test
        else:
            target = y_test
        try:
            weighted = scorer(estimator[name], X_test, target,
                              sample_weight=sample_weight)
            ignored = scorer(estimator[name], X_test[10:], target[10:])
            unweighted = scorer(estimator[name], X_test, target)
            assert_not_equal(weighted, unweighted,
                             msg="scorer {0} behaves identically when "
                             "called with sample weights: {1} vs "
                             "{2}".format(name, weighted, unweighted))
            assert_almost_equal(weighted, ignored,
                                err_msg="scorer {0} behaves differently when "
                                "ignoring samples and setting sample_weight to"
                                " 0: {1} vs {2}".format(name, weighted,
                                                        ignored))

        except TypeError as e:
            assert_true("sample_weight" in str(e),
                        "scorer {0} raises unhelpful exception when called "
                        "with sample weights: {1}".format(name, str(e)))

@ignore_warnings  # UndefinedMetricWarning for P / R scores
def check_scorer_memmap(scorer_name):
    scorer, estimator = SCORERS[scorer_name], ESTIMATORS[scorer_name]
    if scorer_name in MULTILABEL_ONLY_SCORERS:
        score = scorer(estimator, X_mm, y_ml_mm)
    else:
        score = scorer(estimator, X_mm, y_mm)
    assert isinstance(score, numbers.Number), scorer_name

def test_scorer_memmap_input():
    # Non-regression test for #6147: some score functions would
    # return singleton memmap when computed on memmap data instead of scalar
    # float values.
    for name in SCORERS.keys():
        yield check_scorer_memmap, name

def test_deprecated_names():
    X, y = make_blobs(random_state=0, centers=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    clf = LogisticRegression(random_state=0)
    clf.fit(X_train, y_train)

    for name in ('mean_absolute_error', 'mean_squared_error',
                 'median_absolute_error', 'log_loss'):
        warning_msg = "Scoring method %s was renamed to" % name
        for scorer in (get_scorer(name), SCORERS[name]):
            assert_warns_message(DeprecationWarning,
                                 warning_msg,
                                 scorer, clf, X, y)

        assert_warns_message(DeprecationWarning,
                             warning_msg,
                             cross_val_score, clf, X, y, scoring=name)

def test_scoring_is_not_metric():
    assert_raises_regexp(ValueError, 'make_scorer', check_scoring,
                         LogisticRegression(), f1_score)
    assert_raises_regexp(ValueError, 'make_scorer', check_scoring,
                         LogisticRegression(), roc_auc_score)
    assert_raises_regexp(ValueError, 'make_scorer', check_scoring,
                         Ridge(), r2_score)
    assert_raises_regexp(ValueError, 'make_scorer', check_scoring,
                         KMeans(), adjusted_rand_score)


#!/usr/bin/env python
#
# Copyright 2013 Quantopian, 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.

import matplotlib.pyplot as plt

from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_from_yahoo

# Import exponential moving average from talib wrapper
from zipline.transforms.ta import EMA

from datetime import datetime
import pytz

class DualEMATaLib(TradingAlgorithm):
    """Dual Moving Average Crossover algorithm.

    This algorithm buys apple once its short moving average crosses
    its long moving average (indicating upwards momentum) and sells
    its shares once the averages cross again (indicating downwards
    momentum).

    """
    def initialize(self, short_window=20, long_window=40):
        # Add 2 mavg transforms, one with a long window, one
        # with a short window.
        self.short_ema_trans = EMA(timeperiod=short_window)
        self.long_ema_trans = EMA(timeperiod=long_window)

        # To keep track of whether we invested in the stock or not
        self.invested = False

    def handle_data(self, data):
        self.short_ema = self.short_ema_trans.handle_data(data)
        self.long_ema = self.long_ema_trans.handle_data(data)
        if self.short_ema is None or self.long_ema is None:
            return

        self.buy = False
        self.sell = False

        if (self.short_ema > self.long_ema).all() and not self.invested:
            self.order('AAPL', 100)
            self.invested = True
            self.buy = True
        elif (self.short_ema < self.long_ema).all() and self.invested:
            self.order('AAPL', -100)
            self.invested = False
            self.sell = True

        self.record(AAPL=data['AAPL'].price,
                    short_ema=self.short_ema['AAPL'],
                    long_ema=self.long_ema['AAPL'],
                    buy=self.buy,
                    sell=self.sell)

if __name__ == '__main__':
    start = datetime(1990, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(1991, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
                           end=end)

    dma = DualEMATaLib()
    results = dma.run(data).dropna()

    fig = plt.figure()
    ax1 = fig.add_subplot(211, ylabel='portfolio value')
    results.portfolio_value.plot(ax=ax1)

    ax2 = fig.add_subplot(212)
    results[['AAPL', 'short_ema', 'long_ema']].plot(ax=ax2)

    ax2.plot(results.ix[results.buy].index, results.short_ema[results.buy],
             '^', markersize=10, color='m')
    ax2.plot(results.ix[results.sell].index, results.short_ema[results.sell],
             'v', markersize=10, color='k')
    plt.legend(loc=0)
    plt.gcf().set_size_inches(18, 8)


"""
=======================================
Receiver Operating Characteristic (ROC)
=======================================

Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.

ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X axis. This means that the top left corner of the plot is
the "ideal" point - a false positive rate of zero, and a true positive rate of
one. This is not very realistic, but it does mean that a larger area under the
curve (AUC) is usually better.

The "steepness" of ROC curves is also important, since it is ideal to maximize
the true positive rate while minimizing the false positive rate.

ROC curves are typically used in binary classification to study the output of
a classifier. In order to extend ROC curve and ROC area to multi-class
or multi-label classification, it is necessary to binarize the output. One ROC
curve can be drawn per label, but one can also draw a ROC curve by considering
each element of the label indicator matrix as a binary prediction
(micro-averaging).

.. note::

    See also :func:`sklearn.metrics.roc_auc_score`,
             :ref:`example_model_selection_plot_roc_crossval.py`.

"""
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]

# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                    random_state=0)

# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                 random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()

# Plot ROC curve
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
         label='micro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["micro"]))
for i in range(n_classes):
    plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
                                   ''.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()


import requests
import json
import numpy as np
import pandas as pd
import CoHouseToken
from difflib import SequenceMatcher

# In[3]:

def exactMatch(line1, line2):
    line1=line1.upper().rstrip()
    line2=line2.upper().rstrip()
    #print("|"+line1+"|"+line2+"|",line1==line2)
    return line1==line2

def aStopWord(word):
    return word.upper().replace("COMPANY","CO").replace("LIMITED","LTD").replace("&","AND").rstrip()

def spaces(word):
    w = word.upper().replace("/"," ")
    w = w.replace("."," ").replace(","," ").replace("-"," ").rstrip()
    return w

def removeAStopWord(word):
    w = word.upper().replace("LTD"," ").replace("CO"," ").replace("AND"," ").replace("("," ").replace("/"," ")
    w = w.replace(")"," ").replace("."," ").replace(","," ").replace("-"," ").rstrip()
    return w

def removeABlank(word):
    w = word.replace(" ","")
    return w

def removeABracket (line):
    flag = False
    word=""
    for a in line:
        if a=="(":
            flag = True
            a=""
        if a==")":
            a=""
            flag = False
        if flag:
            a=""
        word+=a
    return word

def stopWord(line1, line2):
    line1=aStopWord(line1)
    line2=aStopWord(line2)
    #print("|"+line1+"|"+line2+"|",line1==line2)
    return line1==line2

def removeStopWord(line1, line2):
    line1=spaces(line1)
    line2=spaces(line2)
    line1=aStopWord(line1)
    line2=aStopWord(line2)
    line1=removeAStopWord(line1)
    line2=removeAStopWord(line2)
    #print("|"+line1+"|"+line2+"|",line1==line2)
    return line1==line2

def removeBlanks(line1, line2):
    line1=spaces(line1)
    line2=spaces(line2)
    line1=aStopWord(line1)
    line2=aStopWord(line2)
    line1=removeAStopWord(line1)
    line2=removeAStopWord(line2)
    line1=removeABlank(line1)
    line2=removeABlank(line2)
    return line1==line2

def removeBrackets(line1, line2):
    line1=removeABracket(line1)
    line2=removeABracket(line2)
    line1=spaces(line1)
    line2=spaces(line2)
    line1=aStopWord(line1)
    line2=aStopWord(line2)
    line1=removeAStopWord(line1)
    line2=removeAStopWord(line2)
    line1=removeABlank(line1)
    line2=removeABlank(line2)
   #print("|"+line1+"|"+line2+"|",line1==line2)

    return line1==line2

def strip(line1, line2):
    line1=removeABracket(line1)
    line2=removeABracket(line2)
    line1=spaces(line1)
    line2=spaces(line2)
    line1=aStopWord(line1)
    line2=aStopWord(line2)
    line1=removeAStopWord(line1)
    line2=removeAStopWord(line2)
    line1=removeABlank(line1)
    line2=removeABlank(line2)

    return line1,line2

def match(company,results):
    for i in results['items']:
        line = i['title']
        number = i['company_number']
        if(exactMatch(company,line)):
            return True,line,number

    for i in results['items']:
        line = i['title']
        number = i['company_number']
        if(stopWord(company,line)):
            return True,line,number

    for i in results['items']:
        line = i['title']
        number = i['company_number']
        if(removeStopWord(company,line)):
            return True,line,number

    for i in results['items']:
        line = i['title']
        number = i['company_number']
        if(removeBlanks(company,line)):
            return True,line,number

    for i in results['items']:
        line = i['title']
        number = i['company_number']
        if(removeBrackets(company,line)):
            return True,line,number

        #old_match(company,results)
    return False,"",""

def main(args):
    print(args[0])
    search_url ="https://api.companieshouse.gov.uk/search/companies?q="
    token = CoHouseToken.getToken()
    pw = ''
    base_url = 'https://api.companieshouse.gov.uk'
    file = args[1]
    print(file)
    df = pd.read_csv(file,names=['Organisation'])
    companies = df.Organisation
    count=0
    found = open("found2.csv",'w')
    missing = open("missing2.csv",'w')

    for c in companies:
        c =c.upper().replace("&","AND")
        c = c.split(" T/A ")[0]
        c = c.split("WAS ")[0]
        c= spaces(c)
        url=search_url+c
        results = json.loads(requests.get(url, auth=(token,pw)).text)
        for i , key  in enumerate(results['items']):
            a,b = strip(c, key['title'])
            r = SequenceMatcher(None, a, b).ratio()
            print("%s \t %s\t %.2f \t %s \t %s"%(i,c,r,key['company_number'],key['title']))

        v = input('type number or return to reject: ')
        if v =="":
            print("reject")
            missing.write("%s\n"%(c))
        else:
            key = results['items'][int(v)]
            print("%s \t %s\t %.2f \t %s \t %s"%(v,c,r,key['company_number'],key['title']))
            print("*************************")
            found.write("%s,%s,%s,\n"%(c,key['title'],key['company_number']))

    print()
    #print(count/len(companies))

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))