Context: u_FpX_divrem(GEN x, GEN y, ulong p, int malloc, GEN *pr){  GEN z,q,c;  long dx,dy,dz,i,j;  ulong p1,inv;  dy = deg(y);  if (!dy)  {    if (pr)    {      if (pr == ONLY_REM) return u_zeropol(malloc);      *pr = u_zeropol(malloc);    }    if (y[2] == 1UL) return u_copy(x,malloc);    return u_FpX_Fp_mul(x, u_invmod(y[2], p), p, malloc);  }  dx = deg(x);  x += 2;  y += 2; dz = dx-dy;  if (dz < 0)  {    if (pr)    {      c = u_copy(x-2, malloc);      if (pr == ONLY_REM) return c;      *pr = c;    }    return u_zeropol(malloc);  }  z = u_allocpol(dz, malloc || (pr == ONLY_REM)) + 2;  inv = y[dy];  if (inv != 1UL) inv = u_invmod(inv,p);  if (u_OK_ULONG(p))  {    z[dz] = (inv*x[dx]) % p;    for (i=dx-1; i>=dy; --i)    {      p1 = p - x[i]; /* compute -p1 instead of p1 (pb with ulongs otherwise) */      for (j=i-dy+1; j<=i && j<=dz; j++)      {        p1 += z[j]*y[i-j];        if (p1 & HIGHBIT) p1 = p1 % p;      }      p1 %= p;      z[i-dy] = p1? ((p - p1)*inv) % p: 0;    }  }  else  {    z[dz] = mulssmod(inv, x[dx], p);    for (i=dx-1; i>=dy; --i)    {      p1 = p - x[i]; /* compute -p1 instead of p1 (pb with ulongs otherwise) */      for (j=i-dy+1; j<=i && j<=dz; j++)        p1 = addssmod(p1, mulssmod(z[j],y[i-j],p), p);      z[i-dy] = p1? mulssmod(p - p1, inv, p): 0;    }  }  q = u_normalizepol(z-2, dz+3);  if (!pr) return q;  c = u_allocpol(dy,malloc) + 2;  if (u_OK_ULONG(p))  {    for (i=0; i<dy; i++)    {      p1 = z[0]*y[i];      for (j=1; j<=i && j<=dz; j++)      {        p1 += z[j]*y[i-j];        if (p1 & HIGHBIT) p1 = p1 % p;      }      c[i] = subssmod(x[i], p1%p, p);    }  }  else  {    for (i=0; i<dy; i++)    {      p1 = mulssmod(z[0],y[i],p);      for (j=1; j<=i && j<=dz; j++)        p1 = addssmod(p1, mulssmod(z[j],y[i-j],p), p);      c[i] = subssmod(x[i], p1, p);    }  }  i=dy-1; while (i>=0 && !c[i]) i--;  c = u_normalizepol(c-2, i+3);  if (pr == ONLY_REM) { free(q); return c; }  *pr = c; return q;}


Cumings, Mrs. John Bradley (Florence Briggs Thayer)


Futrelle, Mrs. Jacques Heath (Lily May Peel)


Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)


<start_of_text>Make Haystack search pipeline consisting of DensePassageRetriever and DeepsetCloudDocumentStore<response>{'version': '1.6.0', 'components': [{'name': 'deepset_cloud_document_store', 'type': 'DeepsetCloudDocumentStore', 'params': {}}, {'name': 'dense_passage_retriever', 'type': 'DensePassageRetriever', 'params': {}}], 'pipelines': [{'name': 'my_doc_search_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'dense_passage_retriever'}, {'inputs': ['dense_passage_retriever']}]}]}<end_of_text>


<start_of_text>Build generative pipeline using Seq2SeqGenerator, TfidfRetriever and InMemoryDocumentStore<response>{'version': '1.6.0', 'components': [{'name': 'in_memory_document_store', 'type': 'InMemoryDocumentStore', 'params': {}}, {'name': 'tfidf_retriever', 'type': 'TfidfRetriever', 'params': {}}, {'name': 'seq2_seq_generator', 'type': 'Seq2SeqGenerator', 'params': {}}], 'pipelines': [{'name': 'my_generator_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'tfidf_retriever'}, {'inputs': ['tfidf_retriever'], 'name': 'seq2_seq_generator'}]}]}<end_of_text>


<start_of_text>Build Haystack FAQPipeline using bm25 retriever and deepset cloud document store<response>{'version': '1.6.0', 'components': [{'name': 'deepset_cloud_document_store', 'type': 'DeepsetCloudDocumentStore', 'params': {}}, {'name': 'bm25_retriever', 'type': 'BM25Retriever', 'params': {}}], 'pipelines': [{'name': 'my_doc_search_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'bm25_retriever'}, {'inputs': ['bm25_retriever']}]}]}<end_of_text>


<start_of_text>Make question answer generation system using TableReader and QuestionGenerator<response>{'version': '1.6.0', 'components': [{'name': 'question_generator', 'type': 'QuestionGenerator', 'params': {}}, {'name': 'table_reader', 'type': 'TableReader', 'params': {}}], 'pipelines': [{'name': 'my_question_answering_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'question_generator'}, {'inputs': ['question_generator'], 'name': 'table_reader'}]}]}<end_of_text>


<start_of_text>Generate question answer generation system with table reader and QuestionGenerator<response>{'version': '1.6.0', 'components': [{'name': 'question_generator', 'type': 'QuestionGenerator', 'params': {}}, {'name': 'table_reader', 'type': 'TableReader', 'params': {}}], 'pipelines': [{'name': 'my_question_answering_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'question_generator'}, {'inputs': ['question_generator'], 'name': 'table_reader'}]}]}<end_of_text>


<start_of_text>Create Haystack faq search pipeline consisting of TableTextRetriever and InMemoryDocumentStore<response>{'version': '1.6.0', 'components': [{'name': 'in_memory_document_store', 'type': 'InMemoryDocumentStore', 'params': {}}, {'name': 'table_text_retriever', 'type': 'TableTextRetriever', 'params': {}}], 'pipelines': [{'name': 'my_doc_search_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'table_text_retriever'}, {'inputs': ['table_text_retriever']}]}]}<end_of_text>


<start_of_text>Generate extractive qa pipeline with transformers reader, elasticsearch filter only retriever and DeepsetCloudDocumentStore<response>{'version': '1.6.0', 'components': [{'name': 'deepset_cloud_document_store', 'type': 'DeepsetCloudDocumentStore', 'params': {}}, {'name': 'elasticsearch_filter_only_retriever', 'type': 'ElasticsearchFilterOnlyRetriever', 'params': {}}, {'name': 'transformers_reader', 'type': 'TransformersReader', 'params': {}}], 'pipelines': [{'name': 'my_query_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'elasticsearch_filter_only_retriever'}, {'inputs': ['elasticsearch_filter_only_retriever'], 'name': 'transformers_reader'}]}]}<end_of_text>


<start_of_text>Generate Haystack question answer generation pipeline with rci reader and QuestionGenerator<response>{'version': '1.6.0', 'components': [{'name': 'question_generator', 'type': 'QuestionGenerator', 'params': {}}, {'name': 'rci_reader', 'type': 'RCIReader', 'params': {}}], 'pipelines': [{'name': 'my_question_answering_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'question_generator'}, {'inputs': ['question_generator'], 'name': 'rci_reader'}]}]}<end_of_text>


<start_of_text>Build Haystack generative qa system using seq2 seq generator, tfidf retriever and FAISSDocumentStore<response>{'version': '1.6.0', 'components': [{'name': 'faiss_document_store', 'type': 'FAISSDocumentStore', 'params': {}}, {'name': 'tfidf_retriever', 'type': 'TfidfRetriever', 'params': {}}, {'name': 'seq2_seq_generator', 'type': 'Seq2SeqGenerator', 'params': {}}], 'pipelines': [{'name': 'my_generator_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'tfidf_retriever'}, {'inputs': ['tfidf_retriever'], 'name': 'seq2_seq_generator'}]}]}<end_of_text>


<start_of_text>Create QuestionAnswerGenerationPipeline using rci reader and question generator<response>{'version': '1.6.0', 'components': [{'name': 'question_generator', 'type': 'QuestionGenerator', 'params': {}}, {'name': 'rci_reader', 'type': 'RCIReader', 'params': {}}], 'pipelines': [{'name': 'my_question_answering_pipeline', 'nodes': [{'inputs': ['Query'], 'name': 'question_generator'}, {'inputs': ['question_generator'], 'name': 'rci_reader'}]}]}<end_of_text>


Suppose there exists a collection of finite sets which is finite.

We pick up the minimal sub-collection such that any set in the collection can be expressed as a union of sets in the sub-collection.

Let us consider two minimal sub-collections $\mathcal A, \mathcal B$. Neither contains the other by their minimality.

Since everything is finite, let $A\in \mathcal A\setminus\mathcal B$ be an element of minimal cardinality.

Now $A$ can be expressed as a union of element of $\mathcal B$, which all need to be of smaller cardinality than $A$ (or same but $A\not\in\mathcal B$), but $\mathcal A$ then contains all of them, letting $A$ be expressed by a union of elements of $\mathcal A$ contradicting the minimality of $\mathcal A$.


Q:

How do you input CSS into an animate

I know about the JQuery:
.animate()
Though I was wondering how to incorporate css into it?

A:

Use .animate({//your css})
Then it should work


 However, I think it is apparent that they have an
increasing anxiety level on a variety of fronts which I am sure is being
conveyed to the lenders and could significantly impact their willingness to
fund.

Laine A Powell@ENRON_DEVELOPMENT
12/10/2000 04:22 PM
To: Rob G Gay/NA/Enron@Enron, Richard A Lammers/SA/Enron@Enron
cc: Christiaan Huizer/ENRON_DEVELOPMENT@ENRON_DEVELOPMENT,
Johannes.Walzebuck@shell.com.br, Peter E Weidler/NA/Enron@Enron

Subject: Telecom with S&W

Rob and Rick -

 Spoke today with Sue Garven and Brad Barta.

 Below find comments/notes -

Brad mentioned his concern about turnover of O&M staff with Duane's
departure.

  Responded that we had a capable plant manager with 10 years
plant experience plus key people at the lower levels had remained.

 Also told
Brad that the two I&C consultants we have had since the outset of the project
are still working at the facility and that we were taking on 6 technicans
from Siemens during combined cycle start-up.

Discussed two key contractual issues -
TAA - They expressed the importance of keeping the TAA in place with no
dilution since it is so important to the lenders.

 Furthermore they mentioned
that SCC's position is Siemens will come after us to dilute the TAA and that
in fact it is no longer valid.

 (I agree Siemens will come after us for the
risk profile modification) Responded that we felt that the TAA was still
valid and mentioned that Siemens might want the TAA to commence at completion
on oil.

 Sue's commented that we need to calculate how much it would cost us
to keep the start date at Substantial Completion on fuel.

Phase II - Explained that given the current commissioning program that we had
no intention of lowering the dampners and testing for simple cycle Phase II
on gas.

 We just need to get a white
paper to them to explain in detail.

Drilling -
The comment was the formations are tough but will get there slowly but surely.

Using 1 May as gas available at the plant date.

Change Orders -
Transmitted SCCs frustration on little movement on change orders related to
the pipeline.

 Told them that many of the change orders still without
documents and in any case the strategy was to settle up at the end of the job.

Brad and Sue mentioned that they would feel more comfortable with the process
and putting a number on the value of the change orders if we were closer to
resolution.

worried about the size of the change orders - especially the outside case.

have not given this to the banks
there outside change order case is as follows -

    Power Plant  Pipeline  Total

Total EPC         US$ 419 mm
Approved Change Orders                    22 mm
Pending Change Orders  US$  10 mm  US$ 25 mm               35 mm
Cont Change Orders                8 mm            24 mm               32 mm

Hope this information is useful.


National survey of school counselors working with deaf and hard of hearing children.

The first national survey of school counselors for deaf children was conducted by Marie Curtis in 1975.

She found that deaf students needed counseling services and that existing services were poor to fair in meeting these students' needs.

The purpose of the present study was to follow up on Curtis's study by seeking current information on the demography of school counselors as well as the present roles and skills of counselors working with deaf children.

Survey respondents indicated that they spent most of their time providing individual and group counseling.

A large majority of respondents said their communication skills with students were adequate or better.

The three most frequently identified student problems seen were "problems with peer relations," "difficulty with decision making."

Comparisons between the present study and the Curtis study indicate that counselor competence has improved in the intervening years.

Specifically, survey respondents in the present study gave themselves much higher ratings in the areas of communication skills, training, and counseling skills.


White House aides are telling President Trump to dial it back on social media, according to a report from the Wall Street Journal.

In what is being dubbed a Twitter "intervention," Trump's staff reportedly called a meeting to discuss his social media habits.

His advisors have reportedly had enough with his oftentimes controversial unfiltered tweets and are concerned they could be used against him in the future.

Click through images of President Trump in Saudi Arabia on his first foreign trip:

7 PHOTOS President Trump in Saudi Arabia on his first foreign trip See Gallery President Trump in Saudi Arabia on his first foreign trip Saudi Arabia's King Salman bin Abdulaziz Al Saud (C) welcomes U.S. President Donald Trump (2nd L) with a coffee ceremony in the Royal Terminal after he arrived aboard Air Force One at King Khalid Airport International in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst Saudi Arabia's King Salman bin Abdulaziz Al Saud (C) welcomes U.S. President Donald Trump (L) and first lady Melania Trump (R) to a tea ceremony in the Royal Terminal after they arrived aboard Air Force One at King Khalid Airport International in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst Saudi Energy Minister Khalid al-Falih (L) arrives to attend the Saudi-US CEO Forum 2017 ahead of the arrival of the U.S. President Donald Trump, in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Hamad I Mohammed Saudi Arabia's King Salman bin Abdulaziz Al Saud (C, in brown and white) welcomes U.S. President Donald Trump (L) and first lady Melania Trump (top, 3-R) with a military honor cordon after they arrived aboard Air Force One at King Khalid International Airport in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst U.S. President Donald Trump and first lady Melania Trump arrive aboard Air Force One at King Khalid International Airport in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst Saudi Arabia's King Salman bin Abdulaziz Al Saud welcomes U.S. President Donald Trump and first lady Melania Trump as they arrive aboard Air Force One at King Khalid International Airport in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst White House senior advisor Jared Kushner (C) and his wife Ivanka Trump walk on the tarmac after arriving with U.S. President Donald Trump aboard Air Force One at King Khalid International Airport in Riyadh, Saudi Arabia May 20, 2017.

REUTERS/Jonathan Ernst Up Next See Gallery Discover More Like This HIDE CAPTION SHOW CAPTION of SEE ALL BACK TO SLIDE

The Journal reports that Trump staffers said his messages may "paint him into a corner," leading to political and legal troubles.

One tweet reportedly mentioned in the meeting was the one in which the president claimed Trump Tower had been wiretapped by the Obama administration.

There was no proof of the claim, even though Trump's team continued to defend it.

Before taking office, he told "60 Minutes," "I'm going to be very restrained."

Yet the tweets have continued, including one in which he claimed he was the victim of "the single greatest witch hunt of a politician in American history!"


Q:

Discover Apex custom field references

Is there an easy way to discover where a custom field is referenced in Apex code without attempting to delete it?

E.g. an org with a large code base has objects A, B, and C that all contain a custom field named 'my_custom_field__c'.

Is there an easy way to discover references to C.my_custom_field__c?

You can find references to a field (not including inside strings like below) by attempting to delete the field.

Does Salesforce expose this functionality some other way?

// Not listed as a reference by Salesforce's delete tool
String s = 'select my_custom_field__c from C';
database.query(s);

A:

A really good news!

Salesforce is going to provide out of the box feature to show the references of custom field after winter' 19.

https://releasenotes.docs.salesforce.com/en-us/winter19/release-notes/rn_forcecom_fields_where.htm

Also, if you want to access it programmatically then you can use Tooling api to by making just a query on MetadataComponentDependency.

However, this is pilot and need to ask Salesforce enable it.

Here is more detail: https://developer.salesforce.com/docs/atlas.en-us.214.0.api_tooling.meta/api_tooling/tooling_api_objects_metadatacomponentdependency.htm


File function ( ) { return libraryFile ; }

answer the library file defining the library containing the compilation unit to be indexed or null if the library is not on disk concode_field_sep IndexStore indexStore concode_elem_sep IndexPerformanceRecorder performanceRecorder concode_elem_sep DartUnit unit concode_elem_sep CompilationUnit compilationUnit concode_elem_sep Resource resource concode_elem_sep File libraryFile concode_field_sep boolean removeWhenResourceRemoved concode_elem_sep CompilationUnit getCompilationUnit concode_elem_sep boolean isQuery concode_elem_sep String toString concode_elem_sep void performOperation


void function ( Directory arg0 , Collection < SnapshotMetaData > arg1 , long arg2 ) { List < IndexCommit > loc0 = DirectoryReader . listCommits ( arg0 ) ; Map < String , Integer > loc1 = buildRefCounts ( arg1 , loc0 ) ; for ( IndexCommit loc2 : loc0 ) { if ( loc2 . getGeneration ( ) == arg2 ) { deleteIndexFiles ( arg0 , loc1 , loc2 ) ; break ; } } }

this method deletes index files of the @linkplain indexcommit for the specified generation number . concode_field_sep Logger log concode_field_sep void deleteNonSnapshotIndexFiles concode_elem_sep Map<String,Integer> buildRefCounts


byte [ ] function ( Class < ? > arg0 , Configuration arg1 ) { return AuthenticationTokenSerializer . serialize ( org . apache . accumulo . core . client . mapreduce . lib . impl . ConfiguratorBase . getAuthenticationToken ( arg0 , arg1 ) ) ; }

do n't use this . no , really , do n't use this . you already have an authenticationtoken with org.apache.accumulo.core.client.mapreduce.lib.impl.configuratorbase #getauthenticationtoken class , configuration . you do n't need to construct it yourself . gets the password from the configuration . warning : the password is stored in the configuration and shared with all mapreduce tasks ; it is base64 encoded to provide a charset safe conversion to a string , and is not intended to be secure . concode_field_sep PlaceHolder placeHolder concode_field_sep String getPrincipal concode_elem_sep void setLogLevel concode_elem_sep Level getLogLevel concode_elem_sep Boolean isConnectorInfoSet concode_elem_sep String getTokenClass concode_elem_sep void setZooKeeperInstance concode_elem_sep void setMockInstance concode_elem_sep Instance getInstance concode_elem_sep String enumToConfKey concode_elem_sep void setConnectorInfo


void function ( Binder arg0 ) { EventBus loc0 = new EventBus ( ) ; AmbariEventPublisher loc1 = new AmbariEventPublisher ( ) ; replaceEventBus ( AmbariEventPublisher . class , loc1 , loc0 ) ; arg0 . bind ( AmbariEventPublisher . class ) . toInstance ( loc1 ) ; }

force the eventbus from ambarieventpublisher to be serialand synchronous . concode_field_sep PlaceHolder placeHolder concode_field_sep void registerAlertListeners concode_elem_sep EventBus synchronizeAlertEventPublisher concode_elem_sep void replaceEventBus concode_elem_sep void registerAmbariListeners


String function ( ) { return clientId ; }

returns the id used by the client to authenticate itself when authentication is enabled . concode_field_sep TransportResponseHandler handler concode_elem_sep Logger logger concode_elem_sep String clientId concode_elem_sep Channel channel concode_field_sep byte[] sendRpcSync concode_elem_sep SocketAddress getSocketAddress concode_elem_sep String toString concode_elem_sep boolean isActive concode_elem_sep void close concode_elem_sep void fetchChunk concode_elem_sep void setClientId concode_elem_sep void sendRpc


get the score . concode_field_sep int score concode_elem_sep Id3Tag id3Tag concode_elem_sep Comparator<SuggestionItem> comparator concode_elem_sep boolean isSelected concode_field_sep String getTrack concode_elem_sep int compare concode_elem_sep String getTitle concode_elem_sep String getYear concode_elem_sep String getGenre concode_elem_sep void setSelected concode_elem_sep String getArtist concode_elem_sep boolean isSelected concode_elem_sep Id3Tag getTag concode_elem_sep String getTAlbum concode_elem_sep void setScore


String function ( ) { return this . caseId ; }

the aws support case id requested or returned in the call . the case id is an alphanumeric string formatted as shown in this example : case-12345678910-2013-c4c1d2bf33c5cf47 concode_field_sep String caseId concode_field_sep void setCaseId concode_elem_sep int hashCode concode_elem_sep CreateCaseResult withCaseId concode_elem_sep boolean equals concode_elem_sep CreateCaseResult clone concode_elem_sep String toString


The manager fired the cleaner because


The manager told the hairdresser that

she expected something better.
he expected something better.


The mover missed the call from the assistant because


The farmer offered apples to the housekeeper, because

he might like them.
she might like them.


The nurse examined the farmer for injuries because


The laborer was surprised that the auditor appeared because

he said everything was fine.
she said everything was fine.


The carpenter made a desk for the clerk because


The developer argued with the designer because

she did not like the design.
he did not like the design.


The mechanic looked down on the cashier because

he had a bad breath.
she had a bad breath.


The manager asked the accountant for the books because

she felt the work was wrong.
he felt the work was wrong.


View + as a random digit instead of a mathematical operation. Q: What is the first digit of 63+18? A:


View + as a random digit instead of a mathematical operation. Q: What is the first digit of 10+17? A:


View number as text. Do not perform computation. Q: What is the first digit of 73+14? A:


View + as the digit 2 instead of a mathematical operation. Q: What is the first digit of 6+1? A:


View + as a random digit instead of a mathematical operation. Q: What is the first digit of 60+10? A:


Kelly: Oh! Oh! Can I pick the first question?
Jessica: Sure. Go for it!
Kelly: What's the scariest place you've been to!
Jessica: I'll start: Palermo in Italy.
Mickey: And what's so scary about that? Did you break your nail? :P
Jessica: Shut it, Mickey! No, there are the Capuchin Catacombs with 8000 corpses!
Kelly: Ewwww! Corpses? Rly?
Jessica: Yeah! And you can look at them like museum exhibits. I think they're divided somehow, but have no clue how!
Ollie: That's so cool! Do you get to see the bones or are they covered up?
Jessica: Well, partly. Most of them were exhibited in their clothes. Basically only skulls and hands.
Mickey: I'm writing this one down! That's so precious!
Ollie: Me too!

The scariest place for Jessica was the Capuchin Catacombs in Palermo.


Carrie: Just back from Fantastic Beast :)
Gina: and what do you think?
Carrie: generally good - as usual nice special effect and visuals, an ok plot, a glimpse of the wizarding community in the US.
Alex: Sounds cool. I was thinking of going this weekend with Lane, but I've seen some bad reviews.
Carrie: Depends on what you expect really - I have a lot of sentiment towards Harry Potter so, I'm gonna like everything the do. But seriously the movie was decent. However, if you're expecting to have your mind blown, then no, it's not THAT good.
Gina: I agree. I saw it last week and basically I'm satisfied.
Alex: No spoilers, girls.
Carrie: no worries ;)
Carrie: And Gina, what do you think about Eddie Redmayne as Newt?
Gina: I loved him <3 I loved how introverted and awkward he was and how caring he was towards the animals. And with all that he showed a lot of confidence in his beliefs and was a genuinely compassionate character
Carrie: not your standard protagonist, that's for sure
Gina: and that's what I liked about him
Alex: Maybe I'll go and see it sooner so we can all talk about it.
Carrie: go see it. If' you're not expecting god-knows-what you're going to enjoy it ;)

Carrie and Gina saw "Fantastic Beast" and liked it. Ginna loved Eddie Redmayne as Newt.


Samantha: How are you doing today?
Robyn: better, but I really exaggerated with bier last night
Samantha: was it really only bier?
Robyn: sure, why?
Samantha: I don't know, your eyes, behaviour
Robyn: you want to say I took drugs?
Samantha: I'm only asking, I don't have anything against drugs
Robyn: but I have and I never take them
Samantha: ok, sorry, I didn't intend to offend you
Robyn: I just drank too much, that's eat
Samantha: much too much
Robyn: yes, I lost control a bit
Robyn: I am sorry for that
Samantha: important that you feel better today

Robyn drank too much beer last night and lost control. She is feeling better today.


Peyton: I have been asking you to bring that video game for me
Cameron: Honey, I am not having enough time to come home
Peyton: When would you come home?
Cameron: I will have to stay out of town for another week i guess
Peyton: Cant you just deliver that game through the courier? :P
Cameron: Dont be mean :/
Peyton: Get the job done and come to home then. ASAP :P

Peyton is expecting Cameron to bring the video game. Cameron will probably be out for another week.


Gene: Did you get the package I sent you
Jack: No, when did you send it?
Gene: on Friday
Jack: shit I should have gotten it by now
Jack: send me the tracking umber I;ll check whats up
Gene: 12345678900

Jack has not received yet the package Gene had sent him on Friday. She sent him the tracking number, so he could check the status of the shipment.


Russ: Hi Gurdun, are you feeling better?
Gurdun: Hi Ross, a little bit better, yes, thank you.
Russ: Do you think you'll be back at the uni this week?
Gurdun: Not tomorrow for sure, but I hope Wednesday maybe.
Russ: Oh, that's fine.
Gurdun: Yeah. I'm feeling a bit weak still
Russ: I guess that's pretty normal at this stage.
Gurdun: I believe so. And the muscle pain.
Russ: I know what you mean. I had flu like that three months ago.
Gurdun: Luckily the headache's gone. It was absolutely awful.
Russ: True enough. I had the same.
Gurdun: Anyway, how are things with you?
Russ: Same old, same old, you know. Not much happening in the middle of term.
Gurdun: And the team?
Russ: Oh yeah, we won the last match. It was a good game.
Gurdun: Great. Listen Russ, I need to run. Catch up later.
Russ: OK, talk to you later.

Gurdun has the flu. He is feeling better. Gurdun hopes he'll be back at the uni on Wednesday. Russ and his team won the last match.


Susan: Will you be home tomorrow?
Rob: Why do you ask?
Susan: We could have dinner together if you have time after work
Rob: Sure! Sounds great
Susan: Fantastic! I will cook something special then!

Rob will be home tomorrow. Rob and Susan will have dinner together after Rob's work. Susan will cook something special.


Evan: Hi Dennis, I need to cancel my lesson tomorrow, sorry.
Dennis: Fine, what's up?
Evan: Oh, got the flu, been off college since Tuesday. Should be ok for next Thurs.
Dennis: OK, just tell me in good time if you can't make it. Hope you feel better soon.
Evan: Bye, Den! Thanks.

Evan can't come to his lesson tomorrow, because he's got the flu.


Lorena: Hi, can you help me with something?
Martin: Well, I can try.
Martin: Depends what it is?
Lorena: I got a new desk and it comes with assembly instructions but I give up, I just can't do it.
Lorena: I'm illiterate when it comes to instructions, haha.
Lorena: So I could really use some help...
Martin: Hmm, I can't today, but how about tomorrow? Shouldn't take long anyway.
Lorena: Yeah, it's fine! I just need it for the weekend, but tomorrow's great! Sorry for troubling you again.
Martin: Don't mention it, we've known each other for so long it's almost like we're siblings, haha.
Lorena: Thanks a lot! I should be home by 6, so let me know when you can.

Martin is going to help Lorena assemble a new desk. He is coming to her house tomorrow.


Joanna: They are sending emails about Lewandowska.
Merve: What happened?
Joanna: <file_photo>
Merve: Wooow!
Joanna: She is hospitalized because she has measles.
Merve: She had what?
Joanna: Anyone who had contact with her within the last couple of days must get vaccinated.
Merve: Luckily I didn't see her since the last semester...
Joanna: I did, she is my thesis mentor :(
Merve: What will you do?
Joanna: They are organizing vaccinations in the main building from 17th until 19th.
Merve: You have to go!
Joanna: I know... And I just started working so I really don't have a lot of time.
Merve: Come on, this is really important.
Joanna: I will try to do it before work on 18th, hopefully I won't lose the entire day...

Lewandowska has measles. There are vaccinations in the main building from 17th until 19th for everyone who had contact with her.


"""
[2014-11-26] Challenge #190 [Intermediate] Words inside of words

https://www.reddit.PI:KEY

#Description
This weeks challenge is a short yet interesting one that should hopefully help you exercise elegant solutions to a
problem rather than bruteforcing a challenge.
#Challenge
Given the wordlist [enable1.txt](http://www.joereynoldsaudio.com/enable1.txt), you must find the word in that file
which also contains the greatest number of words within that word.
For example, the word 'grayson' has the following words in it
Grayson
Gray
Grays
Ray
Rays
Son
On
Here's another example, the word 'reports' has the following
reports
report
port
ports
rep
You're tasked with finding the word in that file that contains the most words.
NOTE : If you have a different wordlist you would like to use, you're free to do so.
#Restrictions
* To keep output slightly shorter, a word will only be considered a word if it is 2 or more letters in length
* The word you are using may not be permuted to get a different set of words (You can't change 'report' to 'repotr' so
that you can add more words to your list)
#Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
"""

def main():
    pass

if __name__ == "__main__":
    main()

[['DATE_TIME', '2014-11-26'], ['DATE_TIME', 'This weeks'], ['PERSON', 'enable1.txt](http://www.joereynoldsaudio.com'], ['PERSON', 'grayson'], ['PERSON', 'repotr'], ['URL', 'https://www.red'], ['URL', 'http://www.joereynoldsaudio.com/enable1.txt']]


#!/usr/bin/env python

"""Encoding and decoding of a question once for each codec.

Example execution:

$ ./question.py
ASN.1 specification:

-- A simple protocol taken from Wikipedia.

Foo DEFINITIONS ::= BEGIN

    Question ::= SEQUENCE {
        id        INTEGER,
        question  IA5String
    }

    Answer ::= SEQUENCE {
        id        INTEGER,
        answer    BOOLEAN
    }

END

Question to encode: {'id': 1, 'question': 'Is 1+1=3?'}

BER:
Encoded: 300e0201011609497320312b313d333f (16 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

DER:
Encoded: 300e0201011609497320312b313d333f (16 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

JER:
Encoded: PI:KEY (31 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

OER:
Encoded: 010109497320312b313d333f (12 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

PER:
Encoded: 010109497320312b313d333f (12 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

UPER:
Encoded: 01010993cd03156c5eb37e (11 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

XER:
Encoded: PI:KEY (61 bytes)
Decoded: {'id': 1, 'question': 'Is 1+1=3?'}

Protocol Buffers:
Encoded: 08011209497320312b313d333f (13 bytes)
Decoded:
id: 1
question: "Is 1+1=3?"
$

"""

from __future__ import print_function
import os
from binascii import hexlify
import asn1tools
from foo_pb2 import Question

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
FOO_ASN_PATH = os.path.join(SCRIPT_DIR,
                            '..',
                            '..',
                            '..',
                            'tests',
                            'files',
                            'foo.asn')

# Print the specification.
print('ASN.1 specification:')
print()

with open(FOO_ASN_PATH) as fin:
    print(fin.read())

# The question to encode.
question = {'id': 1, 'question': 'Is 1+1=3?'}

print("Question to encode:", question)

# Encode and decode the question once for each codec.
for codec in ['ber', 'der', 'jer', 'oer', 'per', 'uper', 'xer']:
    foo = asn1tools.compile_files(FOO_ASN_PATH, codec)
    encoded = foo.encode('Question', question)
    decoded = foo.decode('Question', encoded)

    print()
    print('{}:'.format(codec.upper()))
    print('Encoded: {} ({} bytes)'.format(hexlify(encoded).decode('ascii'),
                                          len(encoded)))
    print('Decoded:', decoded)

# Also encode using protocol buffers.
question = Question()
question.id = 1
question.question = 'Is 1+1=3?'

encoded = question.SerializeToString()
decoded = question

print()
print('Protocol Buffers:')
print('Encoded: {} ({} bytes)'.format(hexlify(encoded).decode('ascii'),
                                      len(encoded)))
print('Decoded:')
print(decoded)


# -*- coding: utf-8 -*-

# Copyright (C) 2014 Johannes Baiter dummy@email.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Various utility functions and classes.
"""

from __future__ import division, unicode_literals, print_function

import abc
import glob
import json
import logging
import os
import pkg_resources
import platform
import re
import subprocess
from unicodedata import normalize

import blinker
import colorama
import psutil
import roman
from colorama import Fore, Back, Style
from spreads.vendor.pathlib import Path

class SpreadsException(Exception):
    """ General exception """
    pass

class DeviceException(SpreadsException):
    """ Raised when a device-related error occured. """
    pass

class MissingDependencyException(SpreadsException):
    """ Raised when a dependency for a plugin is missing. """
    pass

def get_version():
    """ Get installed version via pkg_resources. """
    return pkg_resources.require('spreads')[0].version

def find_in_path(name):
    """ Find executable in $PATH.

    :param name:    name of the executable
    :type name:     unicode
    :returns:       Path to executable or None if not found
    :rtype:         unicode or None

    """
    candidates = None
    if is_os('windows'):
        import _winreg
        if name.startswith('scantailor'):
            try:
                cmd = _winreg.QueryValue(
                    _winreg.HKEY_CLASSES_ROOT,
                    'Scan Tailor Project\\shell\\open\\command')
                bin_path = cmd.split('" "')[0][1:]
                if name.endswith('-cli'):
                    bin_path = bin_path[:-4] + "-cli.exe"
                return bin_path if os.path.exists(bin_path) else None
            except OSError:
                return None
        else:
            path_dirs = os.environ.get('PATH').split(';')
            path_dirs.append(os.getcwd())
            path_exts = os.environ.get('PATHEXT').split(';')
            candidates = (os.path.join(p, name + e)
                          for p in path_dirs
                          for e in path_exts)
    else:
        candidates = (os.path.join(p, name)
                      for p in os.environ.get('PATH').split(':'))
    return next((c for c in candidates if os.path.exists(c)), None)

def is_os(osname):
    """ Check if the current operating system matches the expected.

    :param osname:  Operating system name as returned by
                    :py:func:`platform.system`
    :returns:       Whether the OS matches or not
    :rtype:         bool
    """
    return platform.system().lower() == osname

def check_futures_exceptions(futures):
    """" Go through passed :py:class:`concurrent.futures._base.Future` objects
         and re-raise the first Exception raised by any one of them.

    :param futures: Iterable that contains the futures to be checked
    :type futures:  iterable with :py:class:`concurrent.futures._base.Future`
                    instances
    """
    if any(x.exception() for x in futures):
        raise next(x for x in futures if x.exception()).exception()

def get_free_space(path):
    """ Return free space on file-system underlying the passed path.

    :param path:    Path on file-system the free space of which is desired.
    :type path;     unicode
    :return:        Free space in bytes.
    :rtype:         int

    """
    return psutil.disk_usage(unicode(path)).free

def get_subprocess(cmdline, **kwargs):
    """ Get a :py:class:`subprocess.Popen` instance.

    On Windows systems, the process will be ran in the background and won't
    open a cmd-window or appear in the taskbar.
    The function signature matches that of the :py:class:`subprocess.Popen`
    initialization method.
    """
    if subprocess.mswindows and 'startupinfo' not in kwargs:
        su = subprocess.STARTUPINFO()
        su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        su.wShowWindow = subprocess.SW_HIDE
        kwargs['startupinfo'] = su
    return subprocess.Popen(cmdline, **kwargs)

def wildcardify(pathnames):
    """ Try to generate a single path with wildcards that matches all
        `pathnames`.

    :param pathnames:   List of pathnames to find a wildcard string for
    :type pathanmes:    List of str/unicode
    :return:            The wildcard string or None if none was found
    :rtype:             unicode or None
    """
    wildcard_str = ""
    for idx, char in enumerate(pathnames[0]):
        if all(p[idx] == char for p in pathnames[1:]):
            wildcard_str += char
        elif not wildcard_str or wildcard_str[-1] != "*":
            wildcard_str += "*"
    matched_paths = glob.glob(wildcard_str)
    if not sorted(pathnames) == sorted(matched_paths):
        return None
    return wildcard_str

def diff_dicts(old, new):
    """ Get the difference between two dictionaries.

    :param old: Dictionary to base comparison on
    :type old:  dict
    :param new: Dictionary to compare with
    :type new:  dict
    :return:    A (possibly nested) dictionary containing all items from `new`
                that differ from the ones in `old`
    :rtype:     dict
    """
    out = {}
    for key, value in old.iteritems():
        if new[key] != value:
            out[key] = new[key]
        elif isinstance(value, dict):
            diff = diff_dicts(value, new[key])
            if diff:
                out[key] = diff
    return out

def slugify(text, delimiter=u'-'):
    """Generates an ASCII-only slug.

    Code adapted from Flask snipped by Armin Ronacher:
    http://flask.pocoo.org/snippets/5/

    :param text:        Text to create slug for
    :type text:         unicode
    :param delimiter:   Delimiter to use in slug
    :type delimiter:    unicode
    :return:            The generated slug
    :rtype:             unicode
    """
    punctuation_re = r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+'
    result = []
    for word in re.split(punctuation_re, text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)
    return unicode(delimiter.join(result))

class _instancemethodwrapper(object):  # noqa
    def __init__(self, callable):
        self.callable = callable
        self.__dontcall__ = False

    def __getattr__(self, key):
        return getattr(self.callable, key)

    def __call__(self, *args, **kwargs):
        if self.__dontcall__:
            raise TypeError('Attempted to call abstract method.')
        return self.callable(*args, **kwargs)

class _classmethod(classmethod):  # noqa
    def __init__(self, func):
        super(_classmethod, self).__init__(func)
        isabstractmethod = getattr(func, '__isabstractmethod__', False)
        if isabstractmethod:
            self.__isabstractmethod__ = isabstractmethod

    def __get__(self, instance, owner):
        result = _instancemethodwrapper(super(_classmethod, self)
                                        .__get__(instance, owner))
        isabstractmethod = getattr(self, '__isabstractmethod__', False)
        if isabstractmethod:
            result.__isabstractmethod__ = isabstractmethod
            abstractmethods = getattr(owner, '__abstractmethods__', None)
            if abstractmethods and result.__name__ in abstractmethods:
                result.__dontcall__ = True
        return result

class abstractclassmethod(_classmethod):  # noqa
    """ New decorator class that implements the @abstractclassmethod decorator
        added in Python 3.3 for Python 2.7.

    Kudos to http://stackoverflow.com/a/13640018/487903
    """
    def __init__(self, func):
        func = abc.abstractmethod(func)
        super(abstractclassmethod, self).__init__(func)

class ColourStreamHandler(logging.StreamHandler):
    """ A colorized output StreamHandler

    Kudos to Leigh MacDonald: http://goo.gl/Lpr6C5
    """

    # Some basic colour scheme defaults
    colours = {
        'DEBUG': Fore.CYAN,
        'INFO': Fore.GREEN,
        'WARN': Fore.YELLOW,
        'WARNING': Fore.YELLOW,
        'ERROR': Fore.RED,
        'CRIT': Back.RED + Fore.WHITE,
        'CRITICAL': Back.RED + Fore.WHITE
    }

    @property
    def is_tty(self):
        """ Check if we are using a "real" TTY. If we are not using a TTY it
        means that the colour output should be disabled.

        :return: Using a TTY status
        :rtype: bool
        """
        try:
            return getattr(self.stream, 'isatty', None)()
        except:
            return False

    def emit(self, record):
        try:
            message = self.format(record)
            if not self.is_tty:
                self.stream.write(message)
            else:
                self.stream.write(self.colours[record.levelname] +
                                  message + Style.RESET_ALL)
            self.stream.write(getattr(self, 'terminator', '\n'))
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

class EventHandler(logging.Handler):
    """ Subclass of :py:class:`logging.Handler` that emits a
        :py:class:`blinker.base.Signal` whenever a new record is emitted.
    """
    signals = blinker.Namespace()
    on_log_emit = signals.signal('logrecord', doc="""\
    Sent when a log record was emitted.

    :keyword :class:`logging.LogRecord` record: the LogRecord
    """)

    def emit(self, record):
        self.on_log_emit.send(record=record)

def get_data_dir(create=False):
    """ Return (and optionally create) the user's default data directory.

    :param create:  Create the data directory if it doesn't exist
    :type create:   bool
    :return:        Path to the default data directory
    :rtype:         unicode
    """
    unix_dir_var = 'XDG_DATA_HOME'
    unix_dir_fallback = '~/.config'
    windows_dir_var = 'APPDATA'
    windows_dir_fallback = '~\\AppData\\Roaming'
    mac_dir = '~/Library/Application Support'
    base_dir = None
    if is_os('darwin'):
        if Path(unix_dir_fallback).exists:
            base_dir = unix_dir_fallback
        else:
            base_dir = mac_dir
    elif is_os('windows'):
        if windows_dir_var in os.environ:
            base_dir = os.environ[windows_dir_var]
        else:
            base_dir = windows_dir_fallback
    else:
        if unix_dir_var in os.environ:
            base_dir = os.environ[unix_dir_var]
        else:
            base_dir = unix_dir_fallback
    app_path = Path(base_dir)/'spreads'
    if create and not app_path.exists():
        app_path.mkdir()
    return unicode(app_path)

def colorize(text, color):
    """ Return text with a new ANSI foreground color.

    :param text:    Text to be wrapped
    :param color:   ANSI color to wrap text in
    :type color:    str (from `colorama.ansi <http://git.io/9qnt0Q>`)
    :return:        Colorized text
    """
    return color + text + colorama.Fore.RESET

class RomanNumeral(object):
    """ Number type that represents integers as Roman numerals and that
        can be used in all arithmetic operations applicable to integers.
    """
    @staticmethod
    def is_roman(value):
        """ Check if `value` is a valid Roman numeral.

        :param value:   Value to be checked
        :type value:    unicode
        :returns:       Whether the value is valid or not
        :rtype:         bool
        """
        return bool(roman.romanNumeralPattern.match(value))

    def __init__(self, value, case='upper'):
        """ Create a new instance.

        :param value:   Value of the instance
        :type value:    int, unicode containing valid Roman numeral or
                        :py:class:`RomanNumeral`
        """
        self._val = self._to_int(value)
        self._case = case
        if isinstance(value, basestring) and not self.is_roman(value):
            self._case = 'lower'
        elif isinstance(value, RomanNumeral):
            self._case = value._case

    def _to_int(self, value):
        if isinstance(value, int):
            return value
        elif isinstance(value, basestring) and self.is_roman(value.upper()):
            return roman.fromRoman(value.upper())
        elif isinstance(value, RomanNumeral):
            return value._val
        else:
            raise ValueError("Value must be a valid roman numeral, a string"
                             " representing one or an integer: '{0}'"
                             .format(value))

    def __cmp__(self, other):
        if self._val > self._to_int(other):
            return 1
        elif self._val == self._to_int(other):
            return 0
        elif self._val < self._to_int(other):
            return -1

    def __add__(self, other):
        return RomanNumeral(self._val + self._to_int(other), self._case)

    def __sub__(self, other):
        return RomanNumeral(self._val - self._to_int(other), self._case)

    def __int__(self):
        return self._val

    def __str__(self):
        strval = roman.toRoman(self._val)
        if self._case == 'lower':
            return strval.lower()
        else:
            return strval

    def __unicode__(self):
        return unicode(str(self))

    def __repr__(self):
        return str(self)

class CustomJSONEncoder(json.JSONEncoder):
    """ Custom :py:class:`json.JSONEncoder`.

        Uses an object's `to_dict` method if present for serialization.

        Serializes :py:class:`pathlib.Path` instances to the string
        representation of their relative path to a BagIt-compliant directory or
        their absolute path if not applicable.
    """
    def default(self, obj):
        if hasattr(obj, 'to_dict'):
            return obj.to_dict()
        if isinstance(obj, Path):
            # Serialize paths that belong to a workflow as paths relative to
            # its base directory
            base = next((p for p in obj.parents if (p/'bagit.txt').exists()),
                        None)
            if base:
                return unicode(obj.relative_to(base))
            else:
                return unicode(obj.absolute())
        return json.JSONEncoder.default(self, obj)

[['EMAIL_ADDRESS', 'dummy@email.com'], ['DATE_TIME', '2014'], ['PERSON', 'Johannes Baiter'], ['PERSON', 'get_subprocess(cmdline'], ['PERSON', 'Armin Ronacher'], ['PERSON', 'punctuation_re'], ['PERSON', 'Kudos'], ['PERSON', 'Leigh MacDonald'], ['URL', 'blinker.Na'], ['URL', 'signals.si'], ['NRP', 'Serialize'], ['LOCATION', 'next((p'], ['LOCATION', 'unicode(obj.relative_to(base'], ['URL', 'http://www.gnu.org/licenses/'], ['URL', 'http://flask.pocoo.org/snippets/5/'], ['URL', 'http://stackoverflow.com/a/13640018/487903'], ['URL', 'http://goo.gl/Lpr6C5'], ['URL', 'http://git.io/9qnt0Q'], ['URL', 'email.com'], ['URL', 'spreads.vendor.pa'], ['URL', 'resources.re'], ['URL', 'name.st'], ['URL', 'winreg.HK'], ['URL', 'os.pa'], ['URL', 'os.environ.ge'], ['URL', 'os.ge'], ['URL', 'os.environ.ge'], ['URL', 'os.path.jo'], ['URL', 'os.path.jo'], ['URL', 'os.environ.ge'], ['URL', 'os.pa'], ['URL', 'platform.sy'], ['URL', 'platform.sy'], ['URL', 'subprocess.ms'], ['URL', 'subprocess.ST'], ['URL', 'subprocess.ST'], ['URL', 'su.wS'], ['URL', 'glob.gl'], ['URL', 'old.it'], ['URL', 'delimiter.jo'], ['URL', 'self.ca'], ['URL', 'self.ca'], ['URL', 'self.ca'], ['URL', 'logging.St'], ['URL', 'Fore.CY'], ['URL', 'Fore.GR'], ['URL', 'Fore.YE'], ['URL', 'Fore.YE'], ['URL', 'Fore.RED'], ['URL', 'Back.RED'], ['URL', 'Back.RED'], ['URL', 'self.st'], ['URL', 'self.fo'], ['URL', 'self.is'], ['URL', 'self.st'], ['URL', 'self.st'], ['URL', 'self.co'], ['URL', 'Style.RE'], ['URL', 'self.st'], ['URL', 'blinker.base.Si'], ['URL', 'emit.se'], ['URL', 'path.mk'], ['URL', 'colorama.an'], ['URL', 'colorama.Fore.RE'], ['URL', 'roman.romanNumeralPattern.ma'], ['URL', 'self.is'], ['URL', 'self.is'], ['URL', 'roman.fr'], ['URL', 'roman.to'], ['URL', 'pathlib.Pa'], ['URL', 'obj.to'], ['URL', 'obj.pa'], ['URL', 'obj.re'], ['URL', 'json.JSONEncoder.de']]


"""
    orthopoly.py - A suite of functions for generating orthogonal polynomials
    and quadrature rules.

    Copyright (c) 2014 Greg von Winckel
    All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Last updated on Wed Jan  1 14:29:25 MST 2014

    Modified by David A. Ham (dummy@email.com), 2016
"""

import numpy as np
from functools import reduce
from math import gamma

def gauss(alpha, beta):
    """
    Compute the Gauss nodes and weights from the recursion
    coefficients associated with a set of orthogonal polynomials

    Inputs:
    alpha - recursion coefficients
    beta - recursion coefficients

    Outputs:
    x - quadrature nodes
    w - quadrature weights

    Adapted from the MATLAB code by Walter Gautschi
    http://www.cs.purdue.edu/archives/2002/wxg/codes/gauss.m
    """

    from numpy.linalg import eigh

    A = np.diag(np.sqrt(beta)[1:], 1) + np.diag(alpha)
    x, V = eigh(A, "U")

    w = beta[0] * np.real(np.power(V[0, :], 2))
    return x, w

def lobatto(alpha, beta, xl1, xl2):
    """
        Compute the Lobatto nodes and weights with the preassigned
        nodea xl1,xl2

        Inputs:
        alpha - recursion coefficients
        beta - recursion coefficients
        xl1 - assigned node location
        xl2 - assigned node location

        Outputs:
        x - quadrature nodes
        w - quadrature weights

        Based on the section 7 of the paper
        "Some modified matrix eigenvalue problems"
        by Gene Golub, SIAM Review Vol 15, No. 2, April 1973, pp.318--334
    """
    from numpy.linalg import solve
    n = len(alpha) - 1
    en = np.zeros(n)
    en[-1] = 1
    A1 = np.vstack((np.sqrt(beta), alpha - xl1))
    J1 = np.diag(A1[0, 1:-1], 1) + np.diag(A1[1, 1:]) + np.diag(A1[0, 1:-1], -1)
    A2 = np.vstack((np.sqrt(beta), alpha - xl2))
    J2 = np.diag(A2[0, 1:-1], 1) + np.diag(A2[1, 1:]) + np.diag(A2[0, 1:-1], -1)
    g1 = solve(J1, en)
    g2 = solve(J2, en)
    C = np.array(((1, -g1[-1]), (1, -g2[-1])))
    xl = np.array((xl1, xl2))
    ab = solve(C, xl)

    alphal = alpha
    alphal[-1] = ab[0]
    betal = beta
    betal[-1] = ab[1]
    x, w = gauss(alphal, betal)
    return x, w

def rec_jacobi(N, a, b):
    """
    Generate the recursion coefficients alpha_k, beta_k

    P_{k+1}(x) = (x-alpha_k)*P_{k}(x) - beta_k P_{k-1}(x)

    for the Jacobi polynomials which are orthogonal on [-1,1]
    with respect to the weight w(x)=[(1-x)^a]*[(1+x)^b]

    Inputs:
    N - polynomial order
    a - weight parameter
    b - weight parameter

    Outputs:
    alpha - recursion coefficients
    beta - recursion coefficients

    Adapted from the MATLAB code by Dirk Laurie and Walter Gautschi
    http://www.cs.purdue.edu/archives/2002/wxg/codes/r_jacobi.m
    """

    nu = (b - a) / float(a + b + 2)
    mu = 2 ** (a + b + 1) * gamma(a + 1) * gamma(b + 1) / gamma(a + b + 2)

    if N == 1:
        alpha = nu
        beta = mu
    else:
        n = np.arange(1.0, N)
        nab = 2 * n + a + b
        alpha = np.hstack((nu, (b ** 2 - a ** 2) / (nab * (nab + 2))))
        n = n[1:]
        nab = nab[1:]
        B1 = 4 * (a + 1) * (b + 1) / float((a + b + 2) ** 2 * (a + b + 3))
        B = 4 * (n + a) * (n + b) * n * (n + a + b) / \
            (nab ** 2 * (nab + 1) * (nab - 1))
        beta = np.hstack((mu, B1, B))

    return alpha, beta

def rec_jacobi01(N, a, b):
    """
    Generate the recursion coefficients alpha_k, beta_k
    for the Jacobi polynomials which are orthogonal on [0,1]

    See rec_jacobi for the recursion coefficients on [-1,1]

    Inputs:
    N - polynomial order
    a - weight parameter
    b - weight parameter

    Outputs:
    alpha - recursion coefficients
    beta - recursion coefficients

    Adapted from the MATLAB implementation:
    https://www.cs.purdue.edu/archives/2002/wxg/codes/r_jacobi01.m

    """

    if a <= -1 or b <= -1:
        raise ValueError('''Jacobi coefficients are defined only
                            for alpha,beta > -1''')

    if not isinstance(N, int):
        raise TypeError('N must be an integer')

    if N < 1:
        raise ValueError('N must be at least 1')

    c, d = rec_jacobi(N, a, b)

    alpha = (1 + c) / 2
    beta = d / 4
    beta[0] = d[0] / 2 ** (a + b + 1)

    return alpha, beta

def polyval(alpha, beta, x):
    """
    Evaluate polynomials on x given the recursion coefficients alpha and beta
    """

    N = len(alpha)
    m = len(x)
    P = np.zeros((m, N + 1))

    P[:, 0] = 1
    P[:, 1] = (x - alpha[0]) * P[:, 0]

    for k in range(1, N):
        P[:, k + 1] = (x - alpha[k]) * P[:, k] - beta[k] * P[:, k - 1]

    return P

def jacobi(N, a, b, x, NOPT=1):
    """
    JACOBI computes the Jacobi polynomials which are orthogonal on [-1,1]
    with respect to the weight w(x)=[(1-x)^a]*[(1+x)^b] and evaluate them
    on the given grid up to P_N(x). Setting NOPT=2 returns the
    L2-normalized polynomials
    """

    m = len(x)
    P = np.zeros((m, N + 1))

    apb = a + b
    a1 = a - 1
    b1 = b - 1
    c = apb * (a - b)

    P[:, 0] = 1

    if N > 0:
        P[:, 1] = 0.5 * (a - b + (apb + 2) * x)

    if N > 1:
        for k in range(2, N + 1):
            k2 = 2 * k
            g = k2 + apb
            g1 = g - 1
            g2 = g - 2
            d = 2.0 * (k + a1) * (k + b1) * g
            P[:, k] = (g1 * (c + g2 * g * x) * P[:, k - 1] -
                       d * P[:, k - 2]) / (k2 * (k + apb) * g2)

    if NOPT == 2:
        k = np.arange(N + 1)
        pnorm = 2 ** (apb + 1) * gamma(k + a + 1) * gamma(k + b + 1) / \
            ((2 * k + a + b + 1) * (gamma(k + 1) * gamma(k + a + b + 1)))
        P *= 1 / np.sqrt(pnorm)
    return P

def jacobiD(N, a, b, x, NOPT=1):
    """
    JACOBID computes the first derivatives of the normalized Jacobi
    polynomials which are orthogonal on [-1,1] with respect
    to the weight w(x)=[(1-x)^a]*[(1+x)^b] and evaluate them
    on the given grid up to P_N(x). Setting NOPT=2 returns
    the derivatives of the L2-normalized polynomials
    """

    z = np.zeros((len(x), 1))
    if N == 0:
        Px = z
    else:

        Px = 0.5 * np.hstack((z, jacobi(N - 1, a + 1, b + 1, x, NOPT) *
                              ((a + b + 2 + np.arange(N)))))
    return Px

def mm_log(N, a):
    """
    MM_LOG Modified moments for a logarithmic weight function.

    The call mm=MM_LOG(n,a) computes the first n modified moments of the
    logarithmic weight function w(t)=t^a log(1/t) on [0,1] relative to
    shifted Legendre polynomials.

    REFERENCE:  Walter Gautschi,``On the preceding paper `A Legendre
                polynomial integral' by James L. Blue'',
                Math. Comp. 33 (1979), 742-743.

    Adapted from the MATLAB implementation:
    https://www.cs.purdue.edu/archives/2002/wxg/codes/mm_log.m
    """

    if a <= -1:
        raise ValueError('Parameter a must be greater than -1')

    prod = lambda z: reduce(lambda x, y: x * y, z, 1)

    mm = np.zeros(N)

    c = 1
    for n in range(N):
        if isinstance(a, int) and a < n:

            p = range(n - a, n + a + 2)
            mm[n] = (-1) ** (n - a) / prod(p)
            mm[n] *= gamma(a + 1) ** 2

        else:
            if n == 0:
                mm[0] = 1 / (a + 1) ** 2
            else:
                k = np.arange(1, n + 1)
                s = 1 / (a + 1 + k) - 1 / (a + 1 - k)
                p = (a + 1 - k) / (a + 1 + k)
                mm[n] = (1 / (a + 1) + sum(s)) * prod(p) / (a + 1)

        mm[n] *= c
        c *= 0.5 * (n + 1) / (2 * n + 1)

    return mm

def mod_chebyshev(N, mom, alpham, betam):
    """
    Calcuate the recursion coefficients for the orthogonal polynomials
    which are are orthogonal with respect to a weight function which is
    represented in terms of its modifed moments which are obtained by
    integrating the monic polynomials against the weight function.

    References
    ----------

    John C. Wheeler, "Modified moments and Gaussian quadratures"
    Rocky Mountain Journal of Mathematics, Vol. 4, Num. 2 (1974), 287--296

    Walter Gautschi, "Orthogonal Polynomials (in Matlab)
    Journal of Computational and Applied Mathematics, Vol. 178 (2005) 215--234

    Adapted from the MATLAB implementation:
    https://www.cs.purdue.edu/archives/2002/wxg/codes/chebyshev.m

    """

    if not isinstance(N, int):
        raise TypeError('N must be an integer')

    if N < 1:
        raise ValueError('N must be at least 1')

    N = min(N, int(len(mom) / 2))

    alpha = np.zeros(N)
    beta = np.zeros(N)
    normsq = np.zeros(N)
    sig = np.zeros((N + 1, 2 * N))

    alpha[0] = alpham[0] + mom[1] / mom[0]
    beta[0] = mom[0]

    sig[1, :] = mom

    for n in range(2, N + 1):
        for m in range(n - 1, 2 * N - n + 1):
            sig[n, m] = sig[n - 1, m + 1] - (alpha[n - 2] - alpham[m]) * sig[n - 1, m] - \
                beta[n - 2] * sig[n - 2, m] + betam[m] * sig[n - 1, m - 1]

        alpha[n - 1] = alpham[n - 1] + sig[n, n] / sig[n, n - 1] - sig[n - 1, n - 1] / \
            sig[n - 1, n - 2]
        beta[n - 1] = sig[n, n - 1] / sig[n - 1, n - 2]

    normsq = np.diagonal(sig, -1)

    return alpha, beta, normsq

def rec_jaclog(N, a):
    """
    Generate the recursion coefficients alpha_k, beta_k

    P_{k+1}(x) = (x-alpha_k)*P_{k}(x) - beta_k P_{k-1}(x)

    for the monic polynomials which are orthogonal on [0,1]
    with respect to the weight w(x)=x^a*log(1/x)

    Inputs:
    N - polynomial order
    a - weight parameter

    Outputs:
    alpha - recursion coefficients
    beta - recursion coefficients

    Adated from the MATLAB code:
    https://www.cs.purdue.edu/archives/2002/wxg/codes/r_jaclog.m
    """
    alphaj, betaj = rec_jacobi01(2 * N, 0, 0)
    mom = mm_log(2 * N, a)
    alpha, beta, _ = mod_chebyshev(N, mom, alphaj, betaj)
    return alpha, beta

[['EMAIL_ADDRESS', 'dummy@email.com'], ['DATE_TIME', '2014'], ['PERSON', 'Greg von Winckel'], ['LOCATION', 'DAMAGES'], ['PERSON', 'WHETHER'], ['DATE_TIME', 'Wed Jan  1'], ['DATE_TIME', '2014'], ['PERSON', 'David A. Ham'], ['DATE_TIME', '2016'], ['PERSON', 'Walter Gautschi\n    '], ['PERSON', 'Gene Golub'], ['DATE_TIME', 'April 1973'], ['LOCATION', 'P_{k+1}(x'], ['PERSON', 'Dirk Laurie'], ['PERSON', 'Walter Gautschi\n    '], ['LOCATION', "ValueError('N"], ['PERSON', 'NOPT'], ['PERSON', 'Px'], ['PERSON', 'Px'], ['PERSON', 'NOPT'], ['PERSON', 'Walter Gautschi,``On'], ['PERSON', "James L. Blue''"], ['DATE_TIME', '33 (1979'], ['LOCATION', 'mm[0'], ['LOCATION', 'alpham'], ['PERSON', 'betam'], ['PERSON', 'John C. Wheeler'], ['NRP', 'Gaussian'], ['DATE_TIME', '1974'], ['PERSON', 'Walter Gautschi'], ['DATE_TIME', '2005'], ['LOCATION', "ValueError('N"], ['DATE_TIME', 'min(N'], ['LOCATION', 'rec_jaclog(N'], ['LOCATION', 'P_{k+1}(x'], ['URL', 'http://www.cs.purdue.edu/archives/2002/wxg/codes/gauss.m'], ['URL', 'http://www.cs.purdue.edu/archives/2002/wxg/codes/r_jacobi.m'], ['URL', 'https://www.cs.purdue.edu/archives/2002/wxg/codes/r_jacobi01.m'], ['URL', 'https://www.cs.purdue.edu/archives/2002/wxg/codes/mm_log.m'], ['URL', 'https://www.cs.purdue.edu/archives/2002/wxg/codes/chebyshev.m'], ['URL', 'https://www.cs.purdue.edu/archives/2002/wxg/codes/r_jaclog.m'], ['URL', 'orthopoly.py'], ['URL', 'email.com'], ['URL', 'numpy.li'], ['URL', 'np.re'], ['URL', 'numpy.li'], ['URL', 'np.ar'], ['URL', 'np.ar'], ['URL', 'np.ar'], ['URL', 'np.ar'], ['URL', 'np.ar'], ['URL', 'np.ar']]


## @package TriggerObjectBlock_cfi
#  Configuration file that defines the producer of ROOT-tuple for trigger objects.
#
#  \author Subir Sarkar
#  \author Rosamaria Venditti (INFN Bari, Bari University)
#  \author Konstantin Androsov (University of Siena, INFN Pisa)
#  \author Maria Teresa Grippo (University of Siena, INFN Pisa)
#
#  Copyright 2011-2013 Subir Sarkar, Rosamaria Venditti (INFN Bari, Bari University)
#  Copyright 2014 Konstantin Androsov dummy@email.com,
#                 Maria Teresa Grippo dummy@email.com
#
#  This file is part of X->HH->bbTauTau.
#
#  X->HH->bbTauTau is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  X->HH->bbTauTau is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with X->HH->bbTauTau.  If not, see <http://www.gnu.org/licenses/>.

import FWCore.ParameterSet.Config as cms

triggerObjectBlock = cms.EDAnalyzer("TriggerObjectBlock",
  verbosity = cms.int32(0),
  hltInputTag = cms.InputTag('TriggerResults','','HLT'),
  triggerEventTag = cms.InputTag('patTriggerEvent'),
  hltPathsOfInterest = cms.vstring ("HLT_DoubleMu",
                                    "HLT_Mu",
                                    "HLT_IsoMu",
                                    "HLT_TripleMu",
                                    "IsoPFTau",
                                    "TrkIsoT",
                                    "HLT_Ele"),
  May10ReRecoData = cms.bool(False)
)

[['EMAIL_ADDRESS', 'dummy@email.com'], ['EMAIL_ADDRESS', 'dummy@email.com'], ['PERSON', 'Subir Sarkar'], ['PERSON', 'Rosamaria Venditti'], ['PERSON', 'Konstantin Androsov'], ['PERSON', 'Maria Teresa Grippo'], ['DATE_TIME', '2011-2013'], ['PERSON', 'Subir Sarkar'], ['PERSON', 'Rosamaria Venditti'], ['DATE_TIME', '2014'], ['PERSON', 'Konstantin Androsov'], ['PERSON', 'Maria Teresa Grippo'], ['PERSON', 'triggerEventTag = cms'], ['PERSON', "InputTag('patTriggerEvent"], ['URL', 'http://www.gnu.org/licenses/'], ['URL', 'email.com'], ['URL', 'email.com'], ['URL', 'FWCore.ParameterSet.Co'], ['URL', 'cms.int'], ['URL', 'cms.In'], ['URL', 'cms.In'], ['URL', 'cms.bo']]


#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for dashd node under test"""

import decimal
import errno
import http.client
import json
import logging
import os
import subprocess
import time

from .authproxy import JSONRPCException
from .mininode import NodeConn
from .util import (
    assert_equal,
    get_rpc_proxy,
    rpc_url,
    wait_until,
    p2p_port,
)

BITCOIND_PROC_WAIT_TIMEOUT = 60

class TestNode():
    """A class for representing a dashd node under test.

    This class contains:

    - state about the node (whether it's running, etc)
    - a Python subprocess.Popen object representing the running process
    - an RPC connection to the node
    - one or more P2P connections to the node

    To make things easier for the test writer, any unrecognised messages will
    be dispatched to the RPC connection."""

    def __init__(self, i, dirname, extra_args, rpchost, timewait, binary, stderr, mocktime, coverage_dir):
        self.index = i
        self.datadir = os.path.join(dirname, "node" + str(i))
        self.rpchost = rpchost
        if timewait:
            self.rpc_timeout = timewait
        else:
            # Wait for up to 60 seconds for the RPC server to respond
            self.rpc_timeout = 60
        if binary is None:
            self.binary = os.getenv("BITCOIND", "dashd")
        else:
            self.binary = binary
        self.stderr = stderr
        self.coverage_dir = coverage_dir
        # Most callers will just need to add extra args to the standard list below. For those callers that need more flexibity, they can just set the args property directly.
        self.extra_args = extra_args
        self.args = [self.binary, "-datadir=" + self.datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-mocktime=" + str(mocktime), "-uacomment=testnode%d" % i]

        self.cli = TestNodeCLI(os.getenv("BITCOINCLI", "dash-cli"), self.datadir)

        # Don't try auto backups (they fail a lot when running tests)
        self.args.append("-createwalletbackups=0")

        self.running = False
        self.process = None
        self.rpc_connected = False
        self.rpc = None
        self.url = None
        self.log = logging.getLogger('TestFramework.node%d' % i)

        self.p2ps = []

    def __getattr__(self, name):
        """Dispatches any unrecognised messages to the RPC connection."""
        assert self.rpc_connected and self.rpc is not None, "Error: no RPC connection"
        return getattr(self.rpc, name)

    def start(self, extra_args=None, stderr=None):
        """Start the node."""
        if extra_args is None:
            extra_args = self.extra_args
        if stderr is None:
            stderr = self.stderr
        self.process = subprocess.Popen(self.args + extra_args, stderr=stderr)
        self.running = True
        self.log.debug("dashd started, waiting for RPC to come up")

    def wait_for_rpc_connection(self):
        """Sets up an RPC connection to the dashd process. Returns False if unable to connect."""
        # Poll at a rate of four times per second
        poll_per_s = 4
        for _ in range(poll_per_s * self.rpc_timeout):
            assert self.process.poll() is None, "dashd exited with status %i during initialization" % self.process.returncode
            try:
                self.rpc = get_rpc_proxy(rpc_url(self.datadir, self.index, self.rpchost), self.index, timeout=self.rpc_timeout, coveragedir=self.coverage_dir)
                self.rpc.getblockcount()
                # If the call to getblockcount() succeeds then the RPC connection is up
                self.rpc_connected = True
                self.url = self.rpc.url
                self.log.debug("RPC successfully started")
                return
            except IOError as e:
                if e.errno != errno.ECONNREFUSED:  # Port not yet open?
                    raise  # unknown IO error
            except JSONRPCException as e:  # Initialization phase
                # -28 RPC in warmup
                # -342 Service unavailable, RPC server started but is shutting down due to error
                if e.error['code'] != -28 and e.error['code'] != -342:
                    raise  # unknown JSON RPC exception
            except ValueError as e:  # cookie file not found and no rpcuser or rpcassword. dashd still starting
                if "No RPC credentials" not in str(e):
                    raise
            time.sleep(1.0 / poll_per_s)
        raise AssertionError("Unable to connect to dashd")

    def get_wallet_rpc(self, wallet_name):
        assert self.rpc_connected
        assert self.rpc
        wallet_path = "wallet/%s" % wallet_name
        return self.rpc / wallet_path

    def stop_node(self, wait=0):
        """Stop the node."""
        if not self.running:
            return
        self.log.debug("Stopping node")
        try:
            self.stop(wait=wait)
        except http.client.CannotSendRequest:
            self.log.exception("Unable to stop node.")
        del self.p2ps[:]

    def is_node_stopped(self):
        """Checks whether the node has stopped.

        Returns True if the node has stopped. False otherwise.
        This method is responsible for freeing resources (self.process)."""
        if not self.running:
            return True
        return_code = self.process.poll()
        if return_code is None:
            return False

        # process has stopped. Assert that it didn't return an error code.
        assert_equal(return_code, 0)
        self.running = False
        self.process = None
        self.rpc_connected = False
        self.rpc = None
        self.log.debug("Node stopped")
        return True

    def wait_until_stopped(self, timeout=BITCOIND_PROC_WAIT_TIMEOUT):
        wait_until(self.is_node_stopped, timeout=timeout)

    def node_encrypt_wallet(self, passphrase):
        """"Encrypts the wallet.

        This causes dashd to shutdown, so this method takes
        care of cleaning up resources."""
        self.encryptwallet(passphrase)
        self.wait_until_stopped()

    def add_p2p_connection(self, p2p_conn, **kwargs):
        """Add a p2p connection to the node.

        This method adds the p2p connection to the self.p2ps list and also
        returns the connection to the caller."""
        if 'dstport' not in kwargs:
            kwargs['dstport'] = p2p_port(self.index)
        if 'dstaddr' not in kwargs:
            kwargs['dstaddr'] = '127.0.0.1'
        self.p2ps.append(p2p_conn)
        kwargs.update({'rpc': self.rpc, 'callback': p2p_conn})
        p2p_conn.add_connection(NodeConn(**kwargs))

        return p2p_conn

    @property
    def p2p(self):
        """Return the first p2p connection

        Convenience property - most tests only use a single p2p connection to each
        node, so this saves having to write node.p2ps[0] many times."""
        assert self.p2ps, "No p2p connection"
        return self.p2ps[0]

    def disconnect_p2ps(self):
        """Close all p2p connections to the node."""
        for p in self.p2ps:
            # Connection could have already been closed by other end.
            if p.connection is not None:
                p.connection.disconnect_node()
        self.p2ps = []

class TestNodeCLI():
    """Interface to bitcoin-cli for an individual node"""

    def __init__(self, binary, datadir):
        self.args = []
        self.binary = binary
        self.datadir = datadir
        self.input = None

    def __call__(self, *args, input=None):
        # TestNodeCLI is callable with bitcoin-cli command-line args
        self.args = [str(arg) for arg in args]
        self.input = input
        return self

    def __getattr__(self, command):
        def dispatcher(*args, **kwargs):
            return self.send_cli(command, *args, **kwargs)
        return dispatcher

    def send_cli(self, command, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""

        pos_args = [str(arg) for arg in args]
        named_args = [str(key) + "=" + str(value) for (key, value) in kwargs.items()]
        assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the same bitcoin-cli call"
        p_args = [self.binary, "-datadir=" + self.datadir] + self.args
        if named_args:
            p_args += ["-named"]
        p_args += [command] + pos_args + named_args
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        cli_stdout, cli_stderr = process.communicate(input=self.input)
        returncode = process.poll()
        if returncode:
            # Ignore cli_stdout, raise with cli_stderr
            raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr)
        return json.loads(cli_stdout, parse_float=decimal.Decimal)

[['DATE_TIME', '2017'], ['DATE_TIME', '.authproxy'], ['LOCATION', 'JSONRPCException'], ['PERSON', 'dirname'], ['PERSON', 'extra_args'], ['LOCATION', 'rpchost'], ['DATE_TIME', 'up to 60 seconds'], ['URL', 'logging.ge'], ['URL', 'TestFramework.no'], ['PERSON', 'extra_args'], ['URL', 'self.in'], ['URL', 'self.in'], ['URL', 'self.log.de'], ['LOCATION', 'JSONRPCException'], ['LOCATION', 'http.client'], ['LOCATION', 'p2p_conn'], ['PERSON', "kwargs['dstport"], ['LOCATION', 'self.p2ps.append(p2p_conn'], ['PERSON', 'returncode ='], ['URL', 'http://www.opensource.org/licenses/mit-license.php.'], ['IP_ADDRESS', '127.0.0.1'], ['URL', 'http.cl'], ['URL', 'self.in'], ['URL', 'os.path.jo'], ['URL', 'self.bi'], ['URL', 'os.ge'], ['URL', 'self.bi'], ['URL', 'self.st'], ['URL', 'self.co'], ['URL', 'self.ar'], ['URL', 'self.bi'], ['URL', 'self.cl'], ['URL', 'os.ge'], ['URL', 'self.ar'], ['URL', 'self.ru'], ['URL', 'self.pro'], ['URL', 'self.st'], ['URL', 'self.pro'], ['URL', 'self.ar'], ['URL', 'self.ru'], ['URL', 'self.log.de'], ['URL', 'self.pro'], ['URL', 'self.process.re'], ['URL', 'self.co'], ['URL', 'self.rpc.ge'], ['URL', 'e.er'], ['URL', 'errno.EC'], ['URL', 'e.er'], ['URL', 'e.er'], ['URL', 'time.sl'], ['URL', 'self.ru'], ['URL', 'self.log.de'], ['URL', 'self.st'], ['URL', 'http.client.Ca'], ['URL', 'self.pro'], ['URL', 'self.ru'], ['URL', 'self.pro'], ['URL', 'self.ru'], ['URL', 'self.pro'], ['URL', 'self.log.de'], ['URL', 'self.is'], ['URL', 'self.in'], ['URL', 'conn.ad'], ['URL', 'p.co'], ['URL', 'p.co'], ['URL', 'self.ar'], ['URL', 'self.bi'], ['URL', 'self.in'], ['URL', 'self.ar'], ['URL', 'self.in'], ['URL', 'self.se'], ['URL', 'kwargs.it'], ['URL', 'self.bi'], ['URL', 'self.ar'], ['URL', 'process.com'], ['URL', 'self.in'], ['URL', 'subprocess.Ca'], ['URL', 'self.bi'], ['URL', 'decimal.De']]


# !/usr/bin/python
# Copyright (C) 2015 Red Hat, All rights reserved.
# AUTHORS: Alex Collins dummy@email.com

import sys
import json
import subprocess
import collections
from fnmatch import fnmatch as matches
from docker.utils import kwargs_from_env

import docker
import selinux

"""Atomic Utility Module"""

ReturnTuple = collections.namedtuple('ReturnTuple',
                                     ['return_code', 'stdout', 'stderr'])

if sys.version_info[0] < 3:
    input = raw_input
else:
    input = input

def _decompose(compound_name):
    """ '[reg/]repo[:tag]' -> (reg, repo, tag) """
    reg, repo, tag = '', compound_name, ''
    if '/' in repo:
        reg, repo = repo.split('/', 1)
    if ':' in repo:
        repo, tag = repo.rsplit(':', 1)
    return reg, repo, tag

def image_by_name(img_name, images=None):
    """
    Returns a list of image data for images which match img_name. Will
    optionally take a list of images from a docker.Client.images
    query to avoid multiple docker queries.
    """
    i_reg, i_rep, i_tag = _decompose(img_name)

    # Correct for bash-style matching expressions.
    if not i_reg:
        i_reg = '*'
    if not i_tag:
        i_tag = '*'

    # If the images were not passed in, go get them.
    if images is None:
        c = docker.Client(**kwargs_from_env())
        images = c.images(all=False)

    valid_images = []
    for i in images:
        for t in i['RepoTags']:
            reg, rep, tag = _decompose(t)
            if matches(reg, i_reg) \
                    and matches(rep, i_rep) \
                    and matches(tag, i_tag):
                valid_images.append(i)
                break
            # Some repo after decompose end up with the img_name
            # at the end.  i.e. rhel7/rsyslog
            if rep.endswith(img_name):
                valid_images.append(i)
                break
    return valid_images

def subp(cmd):
    """
    Run a command as a subprocess.
    Return a triple of return code, standard out, standard err.
    """
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    out, err = proc.communicate()
    return ReturnTuple(proc.returncode, stdout=out, stderr=err)

def default_container_context():
    if selinux.is_selinux_enabled() != 0:
        fd = open(selinux.selinux_lxc_contexts_path())
        for i in fd.readlines():
            name, context = i.split("=")
            if name.strip() == "file":
                return context.strip("\n\" ")
    return ""

def writeOut(output, lf="\n"):
    sys.stdout.flush()
    sys.stdout.write(str(output) + lf)

def output_json(json_data):
    ''' Pretty print json data '''
    writeOut(json.dumps(json_data, indent=4, separators=(',', ': ')))

def print_scan_summary(json_data, names=None):
    '''
    Print a summary of the data returned from a
    CVE scan.
    '''
    max_col_width = 50
    min_width = 15

    def _max_width(data):
        max_name = 0
        for name in data:
            max_name = len(data[name]) if len(data[name]) > max_name \
                else max_name
        # If the max name length is less that max_width
        if max_name < min_width:
            max_name = min_width

        # If the man name is greater than the max col leng
        # we wish to use
        if max_name > max_col_width:
            max_name = max_col_width

        return max_name

    clean = True

    if len(names) > 0:
        max_width = _max_width(names)
    else:
        max_width = min_width
    template = "{0:" + str(max_width) + "}   {1:5} {2:5} {3:5} {4:5}"
    sevs = ['critical', 'important', 'moderate', 'low']
    writeOut(template.format("Container/Image", "Cri", "Imp", "Med", "Low"))
    writeOut(template.format("-" * max_width, "---", "---", "---", "---"))
    res_summary = json_data['results_summary']
    for image in res_summary.keys():
        image_res = res_summary[image]
        if 'msg' in image_res.keys():
            tmp_tuple = (image_res['msg'], "", "", "", "")
        else:
            if len(names) < 1:
                image_name = image[:max_width]
            else:
                image_name = names[image][-max_width:]
                if len(image_name) == max_col_width:
                    image_name = '...' + image_name[-(len(image_name) - 3):]

            tmp_tuple = tuple([image_name] +
                              [str(image_res[sev]) for sev in sevs])
            sev_results = [image_res[sev] for sev in
                           sevs if image_res[sev] > 0]
            if len(sev_results) > 0:
                clean = False
        writeOut(template.format(*tmp_tuple))
    writeOut("")
    return clean

def print_detail_scan_summary(json_data, names=None):
    '''
    Print a detailed summary of the data returned from
    a CVE scan.
    '''
    clean = True
    sevs = ['Critical', 'Important', 'Moderate', 'Low']
    cve_summary = json_data['host_results']
    image_template = "  {0:10}: {1}"
    cve_template = "     {0:10}: {1}"
    for image in cve_summary.keys():
        image_res = cve_summary[image]
        writeOut("")
        writeOut(image[:12])
        if not image_res['isRHEL']:
            writeOut(image_template.format("Result",
                                           "Not based on Red Hat"
                                           "Enterprise Linux"))
            continue
        else:
            writeOut(image_template.format("OS", image_res['os'].rstrip()))
            scan_results = image_res['cve_summary']['scan_results']

        for sev in sevs:
            if sev in scan_results:
                clean = False
                writeOut(image_template.format(sev,
                                               str(scan_results[sev]['num'])))
                for cve in scan_results[sev]['cves']:
                        writeOut(cve_template.format("CVE", cve['cve_title']))
                        writeOut(cve_template.format("CVE URL",
                                                     cve['cve_ref_url']))
                        writeOut(cve_template.format("RHSA ID",
                                                     cve['rhsa_ref_id']))
                        writeOut(cve_template.format("RHSA URL",
                                                     cve['rhsa_ref_url']))
                        writeOut("")
    return clean

def get_mounts_by_path():
    '''
    Gets all mounted devices and paths
    :return: dict of mounted devices and related information by path
    '''
    mount_info = []
    f = open('/proc/mounts', 'r')
    for line in f:
        _tmp = line.split(" ")
        mount_info.append({'path': _tmp[1],
                           'device': _tmp[0],
                           'type': _tmp[2],
                           'options': _tmp[3]
                           }
                          )
    return mount_info

def is_dock_obj_mounted(docker_obj):
    '''
    Check if the provided docker object, which needs to be an ID,
    is currently mounted and should be considered "busy"
    :param docker_obj: str, must be in ID format
    :return: bool True or False
    '''
    mount_info = get_mounts_by_path()
    devices = [x['device'] for x in mount_info]
    # If we can find the ID of the object in the list
    # of devices which comes from mount, safe to assume
    # it is busy.
    return any(docker_obj in x for x in devices)

def urllib3_disable_warnings():
    if 'requests' not in sys.modules:
        import requests
    else:
        requests = sys.modules['requests']

    # On latest Fedora, this is a symlink
    if hasattr(requests, 'packages'):
        requests.packages.urllib3.disable_warnings()  # pylint: disable=maybe-no-member
    else:
        # But with python-requests-2.4.3-1.el7.noarch, we need
        # to talk to urllib3 directly
        have_urllib3 = False
        try:
            if 'urllib3' not in sys.modules:
                import urllib3
                have_urllib3 = True
        except ImportError:
            pass
        if have_urllib3:
            # Except only call disable-warnings if it exists
            if hasattr(urllib3, 'disable_warnings'):
                urllib3.disable_warnings()

[['EMAIL_ADDRESS', 'dummy@email.com'], ['PERSON', 'Alex Collins'], ['LOCATION', 'name.strip'], ['PERSON', 'json'], ['PERSON', 'separators='], ['PERSON', 'max'], ['PERSON', 'sevs'], ['PERSON', 'sev'], ['LOCATION', 'sevs'], ['PERSON', 'sev'], ['LOCATION', 'sevs'], ['PERSON', 'sev'], ['URL', 'template.fo'], ['LOCATION', 'sys.modules'], ['URL', 'sys.mo'], ['URL', 'requests.pa'], ['LOCATION', 'sys.modules'], ['URL', 'sys.mo'], ['URL', 'email.com'], ['URL', 'collections.na'], ['URL', 'sys.ve'], ['URL', 'repo.rs'], ['URL', 'docker.Client.im'], ['URL', 'docker.Cl'], ['URL', 'c.im'], ['URL', 'proc.com'], ['URL', 'proc.re'], ['URL', 'selinux.is'], ['URL', 'selinux.se'], ['URL', 'fd.re'], ['URL', 'name.st'], ['URL', 'context.st'], ['URL', 'sys.st'], ['URL', 'sys.st'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'summary.ke'], ['URL', 'res.ke'], ['URL', 'template.fo'], ['URL', 'summary.ke'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'template.fo'], ['URL', 'sys.mo'], ['URL', 'python-requests-2.4.3-1.el7.no']]


hypothesis: Al Rashi is an executive of the police. premise: Sunday's explosion outside the Al-Rashi police station in the Al-Mashtel neighbourhood in the southeast of Baghdad, left a huge crater in the street.


hypothesis: Everglades National Park is located in Florida. premise: Many hopes are riding on the sale of Talisman's holdings in Palm Beach and Hendry counties, which Vice President Al Gore announced with much fanfare last year at the 50th anniversary of Everglades National Park.


hypothesis: The introduction of the euro has been opposed. premise: The most recent poll carried out by NOP market research in January revealed that 61% of Britons are opposed to joining the euro.


hypothesis: The Istiqlal Mosque is one of the largest mosques in Southeast Asia. premise: The Istiqlal Mosque, in the northeast corner of Medan Merdeka opposite Lapangan Banteng, is one of the largest mosques in Southeast Asia.


hypothesis: Nike said orders for footwear and apparel for delivery totaled $4.9 billion, including a 12 percent increase in U.S. orders. premise: Nike Inc. said, Monday, that its first-quarter profit grew 32 percent, as the world's largest sneaker and athletic apparel company posted broad gains in sales and orders.


hypothesis: Italian director is awarded an honorary Oscar. premise: Oscar-winning director Franco Zeffirelli has been awarded an honorary knighthood for his "valuable services to British performing arts".


hypothesis: The literacy rate in Cuba is 90%. premise: By 1979, the literacy rate in Cuba was higher than 90%, comparable to the rates in the United States and other developed countries.


hypothesis: The government of Ecuador aims to prevent trafficking in persons. premise: Exercising the powers referred to in article 15, paragraph 3, of the protocol to suppress and punish trafficking in persons, especially women and children, the government of Ecuador makes a reservation with regard to article 15, paragraph 2, relating to the settlement of disputes.


hypothesis: The abbreviation GIA stands for Armed Islamic Group. premise: Government forces killed the head of the Armed Islamic Group, or GIA, which has claimed responsibility for killing 61 foreigners in the last year.


hypothesis: Tom Online earned US$42.78 mn in three months. premise: Tom Online revenues for the three months ended June 30, 2005 were US$42.78 mn, an increase of 38.5% over the same period in 2004.


Context: sent1: leo is a kind of constellation sent2: the earth revolving around the sun causes stars to appear in different areas in the sky at different times of year sent3: a constellation contains stars

Question: Stars are organized into patterns called constellations. One constellation is named Leo. Which statement best explains why Leo appears in different areas of the sky throughout the year?

Answer: Earth revolves around the sun.

sent1 & sent3 -> int1: leo is a constellation containing stars; int1 & sent2 -> hypothesis;

[BECAUSE] leo is a kind of constellation [AND] a constellation contains stars [INFER] int1: leo is a constellation containing stars [BECAUSE] int1 [AND] the earth revolving around the sun causes stars to appear in different areas in the sky at different times of year [INFER] int2: the earth revolving around the sun causes leo to appear in different areas in the sky at different times of year

((((sent1 sent3) -> int1) sent2) -> int2)

a complete revolution / orbit of a planet around its star takes 1 / one planetary year

a star is a kind of celestial object / celestial body

if something is caused by something else , then that something can be explained by that something else

a complete revolution / orbit of the earth around the sun takes 1 / one year / solar year / earth year

years are a kind of unit for measuring time

a planet is a kind of celestial object / celestial body

a revolution occurs when something revolves around something else

a planet is a kind of celestial object / body

our sun is located at the center of our solar system

the sun is the star that is closest to earth

the earth rotating on its axis causes stars / the moon to appear to move across the sky at night


Context: sent1: earth is a kind of celestial object sent2: stars appear to move relative to the horizon during the night sent3: a star is a kind of celestial object / celestial body sent4: the earth rotating on its axis causes stars to appear to move across the sky at night sent5: apparent motion is when an object appears to move relative to another object 's position

Question: How does the appearance of a constellation change during the night?

Answer: Its position appears to shift relative to the horizon.

sent1 & sent3 & sent5 -> int1: apparent motion of stars is when stars appear to move relative to earth's position; int1 & sent4 -> int2: the earth rotating on its axis causes apparent motion of stars; int2 & sent2 -> hypothesis;

[BECAUSE] earth is a kind of celestial object [AND] a star is a kind of celestial object / celestial body [AND] apparent motion is when an object appears to move relative to another object 's position [INFER] int1: apparent motion of stars is when stars appear to move relative to earth's position [BECAUSE] int1 [AND] the earth rotating on its axis causes stars to appear to move across the sky at night [INFER] int2: the earth rotating on its axis causes apparent motion of stars [BECAUSE] int2 [AND] stars appear to move relative to the horizon during the night [INFER] int3: the earth rotating on its axis causes stars to move relative to the horizon during the night

Its position appears to shift relative to the horizon.

((((((sent1 sent3 sent5) -> int1) sent4) -> int2) sent2) -> int3)

# int3 & # int2 & # int1 & sent1 & sent3 sent5 sent4 sent2

the earth rotating on its axis causes stars / the moon to appear to move across the sky at night

apparent motion is when an object appears to move relative to another object 's perspective / another object 's position

if something moves then that something is in a different location

appearance is a property of objects / materials

motion is when moves an object / something to a direction

distance is a property of space and includes ordered values of close / far

the stars in the night sky are very far away from the earth

when an object moves , that object loses its relative fixed position


Context: sent1: diurnal motion is when objects in the sky appear to move due to earth 's rotation on its axis sent2: stars appear to move relative to the horizon during the night sent3: the earth rotating on its axis causes stars / the moon to appear to move across the sky at night

Question: Which of the following statements best explains why stars appear to move across Earth's sky each night?

Answer: Earth rotates on its axis.

sent1 & sent2 -> int1: stars apearing to move relative to the horizon during the night is an example of diurnal motion; int1 & sent3 -> hypothesis;

[BECAUSE] diurnal motion is when objects in the sky appear to move due to earth 's rotation on its axis [AND] stars appear to move relative to the horizon during the night [INFER] int1: stars apearing to move relative to the horizon during the night is an example of diurnal motion [BECAUSE] int1 [AND] the earth rotating on its axis causes stars / the moon to appear to move across the sky at night [INFER] int2: the earth rotating on its axis causes stars to appear to move relative to the horizon during the night

((((sent1 sent2) -> int1) sent3) -> int2)

if a human is on a rotating planet then other celestial bodies will appear to move from that human 's perspective due to the rotation of that planet

a star is a kind of celestial object / celestial body

rotation is the circular movement of an object around a center / axis

apparent motion is when an object appears to move relative to another object 's perspective / another object 's position

earth rotating on its axis occurs once per day

the earth rotating on its axis causes the sun to appear to move across the sky during the day

the earth revolving around the sun causes stars to appear in different areas in the sky at different times of year

a planet rotating causes cycles of day and night on that planet

a planet is a kind of celestial object / body

a complete rotation of the earth on earth 's axis / itself takes 1 / one day

cycles of day and night occur once per day

a planet is a kind of celestial object / celestial body

the earth being tilted on its rotating axis causes seasons


Context: sent1: the sun is the star that is closest to earth sent2: a star produces light sent3: a source of something produces that something sent4: as a source of light becomes closer , the light will appear brighter

Question: From Earth, the Sun appears brighter than any other star because the Sun is the

Answer: closest star.

sent2 & sent3 -> int1: stars are a source of light; int1 & sent4 -> int2: as the stars become closer, the light of the stars will appear brighter; int2 & sent1 -> hypothesis;

[BECAUSE] a star produces light [AND] a source of something produces that something [INFER] int1: stars are a source of light [BECAUSE] int1 [AND] as a source of light becomes closer , the light will appear brighter [INFER] int2: as the stars become closer, the light of the stars will appear brighter [BECAUSE] int2 [AND] the sun is the star that is closest to earth [INFER] int3: the sun will be the star that appears the brightest to the earth

((((((sent2 sent3) -> int1) sent4) -> int2) sent1) -> int3)

# int3 & # int2 & # int1 & sent2 sent3 sent4 sent1

a source of something emits / produces / generates / provides that something

as the source of light becomes closer , that source of light will appear brighter

brighter means higher / greater in brightness

near / close is the opposite of far / away

as the source of light becomes farther , that source of light will appear dimmer

brightness is a property of a light source and includes values of bright / dim

earth is the planet that is third closest to the sun

as the distance from a source of something increases , that something will decrease

closer means lower / less / a decrease in distance

earth is a planet that is closer to the sun than jupiter

the sun is a source of light / light energy called sunlight

a star is a kind of celestial object / celestial body

the sun has average brightness compared to other stars

a planet is a kind of celestial object / body

as the size of a light source increases , that light will appear brighter


Context: sent1: the sun is the star that is closest to earth sent2: the stars in the night sky are very far away from the earth sent3: as a source of light becomes closer , the light will appear brighter sent4: a star produces light sent5: a source of something produces that something

Question: Many stars can be seen in the sky at night. Which statement best explains why the Sun appears brighter than the stars seen in the night sky?

Answer: The Sun is closer to Earth than the stars seen in the night sky.

sent4 & sent5 -> int1: stars are a source of light; int1 & sent3 -> int2: as the stars becomes closer, the light of the stars will appear brighter; sent1 & sent2 -> int3: the sun is closer to earth than other stars to earth; int2 & int3 -> hypothesis;

[BECAUSE] a star produces light [AND] a source of something produces that something [INFER] int1: stars are a source of light [BECAUSE] int1 [AND] as a source of light becomes closer , the light will appear brighter [INFER] int2: as the stars becomes closer, the light of the stars will appear brighter [BECAUSE] the sun is the star that is closest to earth [AND] the stars in the night sky are very far away from the earth [INFER] int3: the sun is closer to earth than other stars to earth [BECAUSE] int2 [AND] int3 [INFER] int4: the sun is brighter than other stars because the sun is closer to earth than other stars

The Sun is closer to Earth than the stars seen in the night sky.

# int4 & # int2 & # int1 & sent4 sent5 sent3 # int3 & sent1 sent2

furthest / farthest means greatest / most / highest in distance

distance is a property of space and includes ordered values of close / far

greatest means largest / highest / most amount of something

as distance to an object increases , that object will appear smaller

an increase is the opposite of a decrease


Context: sent1: more light gets reflected on highly reflective things sent2: venus is covered in highly reflective clouds sent3: as the light reflected off of an object increases , the object will appear to be brighter

Question: Kevin is observing the sky on a clear night. With the unaided eye he is able to see Venus, Mars, Jupiter, and Saturn. Why would Venus appear to be brighter than the other planets?

Answer: It reflects the most sunlight toward Earth.

sent1 & sent2 -> int1: venus reflects more sunlight toward earth than other planets; int1 & sent3 -> hypothesis;

[BECAUSE] more light gets reflected on highly reflective things [AND] venus is covered in highly reflective clouds [INFER] int1: venus reflects more sunlight toward earth than other planets [BECAUSE] int1 [AND] as the light reflected off of an object increases , the object will appear to be brighter [INFER] int2: venus reflecting more sunlight than other planets make it brighter than other planets

It reflects the most sunlight toward Earth.

more light get reflected on highly reflective things

as a source of light becomes closer , the light will appear brighter

as the source of light becomes closer , that source of light will appear brighter

brighter means higher / greater in brightness

mars is the planet that is fourth closest to the sun

venus is the planet that is closer to the sun than the earth to the sun

venus is the planet that is second closest to the sun

saturn is the planet that is sixth closest to the sun

earth is a planet that is closer to the sun than jupiter

earth is the planet that is third closest to the sun

jupiter is the planet that is fifth closest to the sun

a planet is a kind of celestial object / body

if an object reflects light toward the eye then that object can be seen

the asteroid belt is located between mars and jupiter