问:
avoid call CommandLineRunner in junit4
I'm working on a project using spring boot 2.1.1.RELEASE with junit 4.

This is a command line application, that relies on a CommandLineRunner as "main".

The problem is I need to write a unit test that use some @Autowired stuff

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExcludeCommandLineRunner.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }
}
</code>```

```<code>@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@EnableAutoConfiguration
public class ExcludeCommandLineRunner {
}
</code>```

but there is no way for me to avoid the fact that the CommandLineRunner is called... how can I do it?

答:
Depending on how you configured your project, you can rely on Profile to skip your CommandLineRunner. Declare a bean CommandLineRunner with a @Profile("!test") and configure your test class to start the test profile.

Here is a sample that works:

```<code>@SpringBootApplication
public class SkipCommandLineRunner {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "skipcommandlinerunner");
        SpringApplication.run(SkipCommandLineRunner.class);
    }

    @Bean
    @Profile("!test")
    public CommandLineRunner commandLineRunner() {
        return args -> {
            System.out.println("I am being called");
        };
    }
}
</code>```

```<code>@SpringBootTest
@ActiveProfiles("test")
class SkipCommandLineRunnerTest {

    @Test
    void test() {
        System.out.println("Test is here");
    }
}
</code>```

2020-02-14 19:38:29.525  INFO 41437 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@30e143ff, org.springframework.security.web.context.SecurityContextPersistenceFilter@5b59c3d, org.springframework.security.web.header.HeaderWriterFilter@7fd2a67a, org.springframework.security.web.csrf.CsrfFilter@779b4f9c, org.springframework.security.web.authentication.logout.LogoutFilter@484302ee, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@f0c1ae1, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@252d8df6, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@452ec287, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@410f53b2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@46188a89, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@37fca349, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@41404aa2, org.springframework.security.web.session.SessionManagementFilter@3c3cd13a, org.springframework.security.web.access.ExceptionTranslationFilter@5cb8580, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4d174189]

  2020-02-14 19:38:29.586  INFO 41437 --- [           main] c.z.s.c.SkipCommandLineRunnerTest        : Started SkipCommandLineRunnerTest in 3.22 seconds (JVM running for 4.231)

Test is here

You don't see the other I am being called, which shows that the CommandLineRunner is excluded.

Hope it helps

Title: avoid call CommandLineRunner in junit4

Body:
I'm working on a project using spring boot 2.1.1.RELEASE with junit 4.

This is a command line application, that relies on a CommandLineRunner as "main".

The problem is I need to write a unit test that use some @Autowired stuff

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExcludeCommandLineRunner.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }
}

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@EnableAutoConfiguration
public class ExcludeCommandLineRunner {
}

but there is no way for me to avoid the fact that the CommandLineRunner is called... how can I do it?

Body:
Depending on how you configured your project, you can rely on Profile to skip your CommandLineRunner. Declare a bean CommandLineRunner with a @Profile("!test") and configure your test class to start the test profile.

Here is a sample that works:

@SpringBootApplication
public class SkipCommandLineRunner {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "skipcommandlinerunner");
        SpringApplication.run(SkipCommandLineRunner.class);
    }

    @Bean
    @Profile("!test")
    public CommandLineRunner commandLineRunner() {
        return args -> {
            System.out.println("I am being called");
        };
    }
}

@SpringBootTest
@ActiveProfiles("test")
class SkipCommandLineRunnerTest {

    @Test
    void test() {
        System.out.println("Test is here");
    }
}

2020-02-14 19:38:29.525  INFO 41437 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@30e143ff, org.springframework.security.web.context.SecurityContextPersistenceFilter@5b59c3d, org.springframework.security.web.header.HeaderWriterFilter@7fd2a67a, org.springframework.security.web.csrf.CsrfFilter@779b4f9c, org.springframework.security.web.authentication.logout.LogoutFilter@484302ee, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@f0c1ae1, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@252d8df6, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@452ec287, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@410f53b2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@46188a89, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@37fca349, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@41404aa2, org.springframework.security.web.session.SessionManagementFilter@3c3cd13a, org.springframework.security.web.access.ExceptionTranslationFilter@5cb8580, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4d174189]

  2020-02-14 19:38:29.586  INFO 41437 --- [           main] c.z.s.c.SkipCommandLineRunnerTest        : Started SkipCommandLineRunnerTest in 3.22 seconds (JVM running for 4.231)

Test is here

You don't see the other I am being called, which shows that the CommandLineRunner is excluded.

Hope it helps


来源: stackexchange

问:
A problem in using Dataframe :module 'pandas' has no attribute 'Dataframe'
For the following line of code:

```<code>Distance1= pd.Dataframe(columns=['Lat','Lon','PSC','SC_Avg_EcNo','SC_Avg_RSCP','MaxRSCP','MaxEcNo','count','PilotPollutionFlag'])
</code>```

I got the error :

AttributeError: module 'pandas' has no attribute 'Dataframe'

I've seen similar questions like this and most of the answers were that either a file called 'pandas.py' is in the same directory as script, or that another variable called 'pd' is used in the program
but that doesn't happen in my program so what is the problem ?

答:
Typo, it should be DataFrame

```<code>                  ^
</code>```

Note the letter 'F' has to be capitalized.

ContentLicense: CC BY-SA 4.0

Body:
For the following line of code:

Distance1= pd.Dataframe(columns=['Lat','Lon','PSC','SC_Avg_EcNo','SC_Avg_RSCP','MaxRSCP','MaxEcNo','count','PilotPollutionFlag'])

I got the error :

AttributeError: module 'pandas' has no attribute 'Dataframe'

I've seen similar questions like this and most of the answers were that either a file called 'pandas.py' is in the same directory as script, or that another variable called 'pd' is used in the program
but that doesn't happen in my program so what is the problem ?

Body:
Typo, it should be DataFrame

                  ^

Note the letter 'F' has to be capitalized.


问:
EJB 3.0. Provide interfaces to clients
Suppose I am writing enterprise session bean(v 3.0) for using it as remote bean.

I have written remote bussines interface, implemented interface's methods in a bean class(bean also uses another java objects to transfer data to client, that classes specified as serializable to be marshalled over the network) and now I want to provide that bean to clients. To use bean functionality client needs bussiness interface of that bean and also classes that are used to transfer data from bean to client.

To solve this problem I made a jar from that bean and provide it to clients. Clients then have to add this jar library to client's project and after that find the bean implementation using lookup method from Context class.

But when I make a jar it puts all bean classes to jar archive, so client can decompile jar's bytecode and to see the real implementation of my interface. It's not very good practice.

So how can I provide all the necessary interfaces to clients without providing  the real implementation?

答: Put the client interface into a different package or project, and when you build the client jar, only include the class files for that client interface.</p>

ContentLicense: CC BY-SA 3.0

Title: EJB 3.0. Provide interfaces to clients


问:
Android Studio (Java) not receiving sequentially correct Button values
I am currently working on a game where players are supposed to solve for X + Y with selection of 3 buttons (1 of which is answer) and a "Next" button to go to the next question (by replacing values of components into the next question's). However, I am not able to tally the answers because my tested selection (Button) is always testing the values of the next question

To give a little context,

questionCategories is an ArrayList of ArrayList with different levels

e.g. questionCategories.get(selectedLevel) returns ArrayList of different arithmetics

jumbleOptions populates 3 buttons with correct and incorrect answers which are housed in options

I'm having a situation where when answering Question 1, the shown option values belongs to Question 1, but the tested values (in test) are from Question 2.

e.g.

Qn1: 3 + 5 - A: 2, B: 8, C: 4

Qn2: 8 + 2 - A: 10, B: 11, C:12

When I attempt Qn1 on B and click "Next" to go to the next question (and test for correctness), Instead of testing B:8 my program ends up testing B: 11 instead. I have tried to Log the captured values of each Button and Question's answer but they are all correct and I am not sure where did I go wrong.

The code snippet is within onViewCreated, the first question is initialized to display because of placeholder text in the original element. I'm sorry if the code snippet does not make much sense, trying to keep it short so it's (hopefully) more readable.

```<code>// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));

do {
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
            // Increment question number related variable
            numQnAnswered++;
            // Replace displayable elements with next question
            //Question Number
            questionNumber.setText("Question " + String.valueOf(numQnAnswered));

            questionTitle.setText(q.toString());
            jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));

            boolean test = checkAnswer(String.valueOf(q.getAnswer()),
                options.get(SELECTED_OPTION).getText().toString());
            Log.d("Answer Correctness", String.valueOf(test));
        }
    });
    counter++;
} while (counter < NUMBER_OF_QNS);
</code>```

答:
Let's simulate the scenario:
First question is set up manually, and next question is loaded based on button click. I assume numQnAnswered is 0 and you're getting the answer from your Question object of numQnAnswered th position, right?

```<code>final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
</code>```

As your codes say so.
Notice here, carefully:

```<code>// Increment question number related variable
numQnAnswered++;
</code>```

Now the problem however is, the answer is validated inside button click, I think you've forgot the fact that the first question was set up manually... & before checking the answer for that one you've incremented the numQnAnswered variable, thus your question is one step behind your answer. Hope it make sense.

Just decrement the numQnAnswered variable after the validation of current question.

```<code>// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));

do {
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
            // first we need to check answer of previous question
            boolean test = checkAnswer(String.valueOf(q.getAnswer()),
                options.get(SELECTED_OPTION).getText().toString());
            Log.d("Answer Correctness", String.valueOf(test));

            // Increment question number related variable
            numQnAnswered++;
            // Replace displayable elements with next question
            //Question Number
            questionNumber.setText("Question " + String.valueOf(numQnAnswered));

            questionTitle.setText(q.toString());
            jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));

        }
    });
    counter++;
} while (counter < NUMBER_OF_QNS);
</code>```

Body:
I am currently working on a game where players are supposed to solve for X + Y with selection of 3 buttons (1 of which is answer) and a "Next" button to go to the next question (by replacing values of components into the next question's). However, I am not able to tally the answers because my tested selection (Button) is always testing the values of the next question

To give a little context,

questionCategories is an ArrayList of ArrayList with different levels

e.g. questionCategories.get(selectedLevel) returns ArrayList of different arithmetics

jumbleOptions populates 3 buttons with correct and incorrect answers which are housed in options

I'm having a situation where when answering Question 1, the shown option values belongs to Question 1, but the tested values (in test) are from Question 2.

e.g.

Qn1: 3 + 5 - A: 2, B: 8, C: 4

Qn2: 8 + 2 - A: 10, B: 11, C:12

When I attempt Qn1 on B and click "Next" to go to the next question (and test for correctness), Instead of testing B:8 my program ends up testing B: 11 instead. I have tried to Log the captured values of each Button and Question's answer but they are all correct and I am not sure where did I go wrong.

The code snippet is within onViewCreated, the first question is initialized to display because of placeholder text in the original element. I'm sorry if the code snippet does not make much sense, trying to keep it short so it's (hopefully) more readable.

// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));

do {
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
            // Increment question number related variable
            numQnAnswered++;
            // Replace displayable elements with next question
            //Question Number
            questionNumber.setText("Question " + String.valueOf(numQnAnswered));

            questionTitle.setText(q.toString());
            jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));

            boolean test = checkAnswer(String.valueOf(q.getAnswer()),
                options.get(SELECTED_OPTION).getText().toString());
            Log.d("Answer Correctness", String.valueOf(test));
        }
    });
    counter++;
} while (counter < NUMBER_OF_QNS);

Body:
Let's simulate the scenario:
First question is set up manually, and next question is loaded based on button click. I assume numQnAnswered is 0 and you're getting the answer from your Question object of numQnAnswered th position, right?

final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);

As your codes say so.
Notice here, carefully:

// Increment question number related variable
numQnAnswered++;

Now the problem however is, the answer is validated inside button click, I think you've forgot the fact that the first question was set up manually... & before checking the answer for that one you've incremented the numQnAnswered variable, thus your question is one step behind your answer. Hope it make sense.

Just decrement the numQnAnswered variable after the validation of current question.

// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));

do {
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
            // first we need to check answer of previous question
            boolean test = checkAnswer(String.valueOf(q.getAnswer()),
                options.get(SELECTED_OPTION).getText().toString());
            Log.d("Answer Correctness", String.valueOf(test));

            // Increment question number related variable
            numQnAnswered++;
            // Replace displayable elements with next question
            //Question Number
            questionNumber.setText("Question " + String.valueOf(numQnAnswered));

            questionTitle.setText(q.toString());
            jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));

        }
    });
    counter++;
} while (counter < NUMBER_OF_QNS);


问:
How can is select XML tag that contains specific XML tag with specific text inside using regual expressions?
I have XML text. In that XML text I have tags named <pskc:KeyPackage> this tag may or may not contain different tags and one of that tag may be <pskc:IssueNo>1</pskc:IssueNo>. With regular expressions i want to select all <pskc:KeyPackage> tags, which contain <pskc:IssueNo>1</pskc:IssueNo> tag. How can i accomplish this?

please see regex on flowing link: https://regex101.com/r/7HICeu/2

This is my sample input:

```<code><pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
</code>```

i want to mach following tags:

```<code><pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>
</code>```

and i also want to match each tag that look like this:

```<code>  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
</code>```

I want to say again that <pskc:KeyPackage> tag will contain many different tags, like it does in following example:

```<code><pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>
</code>```

I want to mach the whole <pskc:KeyPackage> tag only if it contains <pskc:IssueNo>1</pskc:IssueNo>. How can i accomplish this?

P.S. I have also tried many different regex-es, on of them is following regex: <pskc:KeyPackage>[\s\S]*<pskc:IssueNo>1<\/pskc:IssueNo>[\s\S]*<pskc:KeyPackage> but it maches whole xml string.

Thank you

答:
This works:

```<code>/<pskc:KeyPackage>((?!<\/pskc:KeyPackage>).)*<pskc:IssueNo>1<\/pskc:IssueNo>.*?<\/pskc:KeyPackage>/gs
</code>```

(I don't know all regex flavors, but it looks like this works for Perl, JS, and Python.)

How it works:

it matches <pskc:KeyPackage>,

followed by any amount (the first *) of any characters (the first .) including newlines (the s flag), each of which matches where </pskc:KeyPackage> does not match ((?!…)),

followed by <pskc:IssueNo>1</pskc:IssueNo>.

Then it also matches up the the closest (.*?) closing </pskc:KeyPackage>.

Other two details:

/s need to be escaped, \/,

depending on your application, you might want to use non-capturing parentheses for the first group (change the first ( to (?:), whose sole purpose is to let you apply the first * to it.

Body:
I have XML text. In that XML text I have tags named <pskc:KeyPackage> this tag may or may not contain different tags and one of that tag may be <pskc:IssueNo>1</pskc:IssueNo>. With regular expressions i want to select all <pskc:KeyPackage> tags, which contain <pskc:IssueNo>1</pskc:IssueNo> tag. How can i accomplish this?

please see regex on flowing link: https://regex101.com/r/7HICeu/2

This is my sample input:

<pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>2</pskc:IssueNo>

  </pskc:KeyPackage>
  <pskc:KeyPackage>

      <pskc:IssueNo>3</pskc:IssueNo>

  </pskc:KeyPackage>

i want to mach following tags:

<pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>

and i also want to match each tag that look like this:

  <pskc:KeyPackage>

      <pskc:IssueNo>1</pskc:IssueNo>

  </pskc:KeyPackage>

I want to say again that <pskc:KeyPackage> tag will contain many different tags, like it does in following example:

<pskc:KeyPackage>

 <testTag>val1</testTag>

  <pskc:IssueNo>1</pskc:IssueNo>

  <testTag2>val2</testTag2>

</pskc:KeyPackage>

I want to mach the whole <pskc:KeyPackage> tag only if it contains <pskc:IssueNo>1</pskc:IssueNo>. How can i accomplish this?

P.S. I have also tried many different regex-es, on of them is following regex: <pskc:KeyPackage>[\s\S]*<pskc:IssueNo>1<\/pskc:IssueNo>[\s\S]*<pskc:KeyPackage> but it maches whole xml string.

Thank you

Body:
This works:

/<pskc:KeyPackage>((?!<\/pskc:KeyPackage>).)*<pskc:IssueNo>1<\/pskc:IssueNo>.*?<\/pskc:KeyPackage>/gs

(I don't know all regex flavors, but it looks like this works for Perl, JS, and Python.)

How it works:

it matches <pskc:KeyPackage>,

followed by any amount (the first *) of any characters (the first .) including newlines (the s flag), each of which matches where </pskc:KeyPackage> does not match ((?!…)),

followed by <pskc:IssueNo>1</pskc:IssueNo>.

Then it also matches up the the closest (.*?) closing </pskc:KeyPackage>.

Other two details:

/s need to be escaped, \/,

depending on your application, you might want to use non-capturing parentheses for the first group (change the first ( to (?:), whose sole purpose is to let you apply the first * to it.


问:
Editing the footer in GitHub pages jekyll's default minima theme
I've followed this tutorial and the following ones to create a Github Pages website with Jekyll. Now I have the minima theme, but it seems to be a different version from the official repo, as the parameters in the repo's _config.yml don't work on mine (e.g. for the Twitter link I have a twitter_username parameter while the repo's twitter under social_links doesn't work).

What is weird is that in the footer I have the title parameter repeated twice, as it renders in both the footer-heading and p-name elements in the index.html. Is there any way to change what is rendered to those elements in the html?

答:
When github advise you to copy master files to override minima gem's files "hidden files deep inside somewhere on you file system" by copying master files, they commit a mistake because breaking changes can append.

The best way to override files on a jekyll theme (for now) is to copy gem's file to your working folder.

```<code>cd /you/working/jekyll
cp -R `echo "$(bundle info minima --path)/_*/"` .
cp -R "$(bundle info minima --path)/assets/" .
</code>```

You then have everything needed to override minima in your working folder (_includes, _layouts, _sass and assets folders).

If you have a github page, you just have to commit and push to you publication branch.

Body:
When github advise you to copy master files to override minima gem's files "hidden files deep inside somewhere on you file system" by copying master files, they commit a mistake because breaking changes can append.

The best way to override files on a jekyll theme (for now) is to copy gem's file to your working folder.

cd /you/working/jekyll
cp -R `echo "$(bundle info minima --path)/_*/"` .
cp -R "$(bundle info minima --path)/assets/" .

You then have everything needed to override minima in your working folder (_includes, _layouts, _sass and assets folders).

If you have a github page, you just have to commit and push to you publication branch.


问:
Can Spock Mock a Java constructor
Trying to broaden the appeal of Spock at work and run into this issue.  Actually trying to write Unit Tests for a Groovy class, but one that calls out to Java.  A static method calls a private constructor.  The code looks like:

```<code>private MyConfigurator(String zkConnectionString){
    solrZkClient = new SolrZkClient(zkConnectionString, 30000, 30000,
            new OnReconnect() {
                @Override
                public void command() { . . . }
            });
}
</code>```

"SolrZkClient" is from third party (Apache) Java library.  Since it tries to connect to ZooKeeper, I would like to mock that out for this Unit Test (rather than running one internally as part of the unit test).

My test gets to the constructor without difficulty, but I can't get past that ctor:

```<code>def 'my test'() {
    when:
        MyConfigurator.staticMethodName('hostName:2181')
    then:
        // assertions
}
</code>```

Is there anyway to do this?

答:
```<code>def anySubscriber = GroovySpy(RealSubscriber, global: true)

1 * new RealSubscriber("Fred")
</code>```

put that into def setup(){ } block or inside of given: label block

Title: Can Spock Mock a Java constructor

Body:
Trying to broaden the appeal of Spock at work and run into this issue.  Actually trying to write Unit Tests for a Groovy class, but one that calls out to Java.  A static method calls a private constructor.  The code looks like:

private MyConfigurator(String zkConnectionString){
    solrZkClient = new SolrZkClient(zkConnectionString, 30000, 30000,
            new OnReconnect() {
                @Override
                public void command() { . . . }
            });
}

"SolrZkClient" is from third party (Apache) Java library.  Since it tries to connect to ZooKeeper, I would like to mock that out for this Unit Test (rather than running one internally as part of the unit test).

My test gets to the constructor without difficulty, but I can't get past that ctor:

def 'my test'() {
    when:
        MyConfigurator.staticMethodName('hostName:2181')
    then:
        // assertions
}

Is there anyway to do this?

Body:
def anySubscriber = GroovySpy(RealSubscriber, global: true)

1 * new RealSubscriber("Fred")

put that into def setup(){ } block or inside of given: label block


问:
Writing text and numeric variable to text file
This is my code:

```<code>ahk_second_number = 4
file = open("D:/Arch (all versions)/Work/SCIPE/Data upload script/count_txt_file/patient_count.txt", "w")
file.write("0\n%" % str(ahk_second_number))
file.close() #This close() is important
</code>```

I want to get a  patient_count.txt which will contain 0 on first line and content of ahk_second_number variable on second line.

It gives me error:

```<code>runfile('D:/del/untitled0.py', wdir='D:/del')
Traceback (most recent call last):

  File "<ipython-input-15-23b229935f25>", line 1, in <module>
    runfile('D:/del/untitled0.py', wdir='D:/del')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/del/untitled0.py", line 3, in <module>
    file.write("0\n%" % str(ahk_second_number))

ValueError: incomplete format
</code>```

Question: How to correct my code above so it will give me patient_count.txt that I need (described above)?

答:
Try this code line instead the one you stated:

```<code>file.write("0\n%d" % ahk_second_number)
</code>```

You were missing the format of your variable you are trying to write. %d means it writes integer values, hence no need to convert your integer to string.

You can get some more details about formatting when writing variables here. Also you can read about formatting in the official documentation.

Body:
This is my code:

ahk_second_number = 4
file = open("D:/Arch (all versions)/Work/SCIPE/Data upload script/count_txt_file/patient_count.txt", "w")
file.write("0\n%" % str(ahk_second_number))
file.close() #This close() is important

I want to get a  patient_count.txt which will contain 0 on first line and content of ahk_second_number variable on second line.

It gives me error:

runfile('D:/del/untitled0.py', wdir='D:/del')
Traceback (most recent call last):

  File "<ipython-input-15-23b229935f25>", line 1, in <module>
    runfile('D:/del/untitled0.py', wdir='D:/del')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/del/untitled0.py", line 3, in <module>
    file.write("0\n%" % str(ahk_second_number))

ValueError: incomplete format

Question: How to correct my code above so it will give me patient_count.txt that I need (described above)?

Body:
Try this code line instead the one you stated:

file.write("0\n%d" % ahk_second_number)

You were missing the format of your variable you are trying to write. %d means it writes integer values, hence no need to convert your integer to string.

You can get some more details about formatting when writing variables here. Also you can read about formatting in the official documentation.


问:
MVC Checkfor / Bootstrap
Im having some trouble adding bootstrap styling to CheckBoxFor and LabelFor in mvc. Its rendering how I would like, but its displaying the text IsChecked. How do I remove the rendered text?

```<code><div class="slider">
    @Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
    @Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })
</div>
</code>```

答:
You can use data annotation for that.

In .cs file, you can mention the Display attribute for property

[Display(Name = "Text for Checkbox")]
public bool IsChecked{ get; set; }
```

<p>Keep your html as it is</p>

```@Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
@Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })
```

This will give you a checkbox along with 'Text for Checkbox'

Title: MVC Checkfor / Bootstrap

Body:
Im having some trouble adding bootstrap styling to CheckBoxFor and LabelFor in mvc. Its rendering how I would like, but its displaying the text IsChecked. How do I remove the rendered text?

    @Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
    @Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })

Body:
You can use data annotation for that.

In .cs file, you can mention the Display attribute for property

[Display(Name = "Text for Checkbox")]
public bool IsChecked{ get; set; }

Keep your html as it is

@Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
@Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })

This will give you a checkbox along with 'Text for Checkbox'


问:
Delete all elements in a list except two o three
Assuming I have this list

```<code> [['GA', 11], ['GO', 25], ['GE', 23], ['DA', 22], ['DE', 33], ['DU', 54], ['DD', 55], ['DF', 27]
</code>```

Given this example of a short list compared to a list of 500 items, how could I remove all items from this list except for GA, GO?

答:
```<code>l2 = [e for e in l if e[0] in ('GA','GO')]
</code>```

Or

```<code>l2 = []
for e in l:
  if e[0] in ('GA', 'GO'):
    l2.append(e)
</code>```

Note also that you don't want to modify the list while iterating over it, create a new list (l2).

Body:
Assuming I have this list

 [['GA', 11], ['GO', 25], ['GE', 23], ['DA', 22], ['DE', 33], ['DU', 54], ['DD', 55], ['DF', 27]

Given this example of a short list compared to a list of 500 items, how could I remove all items from this list except for GA, GO?

Body:
l2 = [e for e in l if e[0] in ('GA','GO')]

Or

l2 = []
for e in l:
  if e[0] in ('GA', 'GO'):
    l2.append(e)

Note also that you don't want to modify the list while iterating over it, create a new list (l2).


问:
Spring Integration DSL Filter vs. RouteToRecipients w/ single Recipient and DefaultOutputToParentFlow
I am needing to route a message from my parent flow into a new flow when a given evaluation returns false but have it continue in the parent flow when that evaluation returns true. Currently I have been able to successfully implement this functionality using the Spring Integration DSL .filter() method without any issues. However, I feel as if though using .filter() in this way does not fall under the true intention of this method. Is there a certain type of router that can be used to better achieve this same need? Is it necessary to change from this .filter() implementation to a router based implementation?

Given the below Integration Flow configuration as an example...

```<code>@Bean
public IntegrationFlow flow() {
    return IntegrationFlows
            .from("inboundChannel")
            .filter(someService::someTrueFalseMethod, onFalseReturn -> onFalseReturn.discardChannel("otherFlowInboundChannel"))
            .handle(someService::someHandleMethod)
            .get();
}

@Bean
public IntegrationFlow otherFlow() {
    return IntegrationFlows
            .from("otherFlowInboundChannel")
            .handle(someOtherService::someOtherHandleMethod)
            .get();
}
</code>```

Up to this point it seems .routeToRecipents() might be what I need to use. In my scenario, I need to evaluate the headers of the message so that is why the recipientMessageSelector is being used.

```<code>@Bean
public IntegrationFlow flow() {
    return IntegrationFlows
            .from("inboundChannel"
            .routeToRecipients(router -> router
                .recipientMessageSelector("otherFlowInboundChannel", someService::someTrueFalseMethod)
                .defaultOutputToParentFlow()
            )
            .handle(someService::someHandleMethod)
            .get();
}

@Bean
public IntegrationFlow otherFlow() {
    return IntegrationFlows
            .from("otherFlowInboundChannel")
            .handle(someOtherService::someOtherHandleMethod)
            .get();
}
</code>```

Even with this routeToRecipients solution that appears to work, is there really any benefit gained between it and the filter implementation above?

答:
Well, it is really not about a Java DSL methods and how to use them. It is really about a theory around those IE patterns.

Let's compare Filter and RecipientListRouter from EIP!

Filter - https://www.enterpriseintegrationpatterns.com/patterns/messaging/Filter.html:

If the message content matches the criteria specified by the Message Filter, the message is routed to the output channel. If the message content does not match the criteria, the message is discarded.

So, technically filter doesn't match your expectations since on false resolution you kinda discard message. However for possible processing on those discarded messages Spring Integration provides a discardChannel option to initiate a discard sub-flow. So, we can treat it as if..else construction...

Recipient List - https://www.enterpriseintegrationpatterns.com/patterns/messaging/RecipientList.html

Then use a Recipient List to inspect an incoming message, determine the list of desired recipients, and forward the message to all channels associated with the recipients in the list.

So, kinda what you need, because you evaluate a message and recipients for it and then send to their channels. Only the problem with this that emulate a filter behavior because you are not going to have a more than two channels with mutually exclusive purpose.

When the filter approach feels like a flow control abusing (reminds me a similar logic in Java relied on the exception handling for flow control), it doesn't dictate us to stay with always canonical behavior to end up with an error when message doesn't fit a condition.

The recipientList is for more complicated scenarios when a selector is used for any arbitrary evaluation, not just plain boolean and has an ability to distribute the same message into several output channels. So, I wouldn't recommend it for this simple true/false scenario.

You may consider to look into another similar pattern:

Content Based Router - https://www.enterpriseintegrationpatterns.com/patterns/messaging/ContentBasedRouter.html

Use a Content-Based Router to route each message to the correct recipient based on message content.

This one feels like very close to what you need with true/false and it is not going to abuse errors (discards) for flow cotrol and doesn't dictate us a list of recipients. And this one also has that defaultOutputToParentFlow() when you would like to rely on non-mapped result.

IMHO, I would stay with filter() - with its true/false logic and discardChannel it really looks like particular implementation of that Content Based Router :-).

Body:
I am needing to route a message from my parent flow into a new flow when a given evaluation returns false but have it continue in the parent flow when that evaluation returns true. Currently I have been able to successfully implement this functionality using the Spring Integration DSL .filter() method without any issues. However, I feel as if though using .filter() in this way does not fall under the true intention of this method. Is there a certain type of router that can be used to better achieve this same need? Is it necessary to change from this .filter() implementation to a router based implementation?

Given the below Integration Flow configuration as an example...

@Bean
public IntegrationFlow flow() {
    return IntegrationFlows
            .from("inboundChannel")
            .filter(someService::someTrueFalseMethod, onFalseReturn -> onFalseReturn.discardChannel("otherFlowInboundChannel"))
            .handle(someService::someHandleMethod)
            .get();
}

@Bean
public IntegrationFlow otherFlow() {
    return IntegrationFlows
            .from("otherFlowInboundChannel")
            .handle(someOtherService::someOtherHandleMethod)
            .get();
}

Up to this point it seems .routeToRecipents() might be what I need to use. In my scenario, I need to evaluate the headers of the message so that is why the recipientMessageSelector is being used.

@Bean
public IntegrationFlow flow() {
    return IntegrationFlows
            .from("inboundChannel"
            .routeToRecipients(router -> router
                .recipientMessageSelector("otherFlowInboundChannel", someService::someTrueFalseMethod)
                .defaultOutputToParentFlow()
            )
            .handle(someService::someHandleMethod)
            .get();
}

@Bean
public IntegrationFlow otherFlow() {
    return IntegrationFlows
            .from("otherFlowInboundChannel")
            .handle(someOtherService::someOtherHandleMethod)
            .get();
}

Even with this routeToRecipients solution that appears to work, is there really any benefit gained between it and the filter implementation above?


问:
color switch after the 2nd button click
how can i use the "switch statement" to switch the colors from button 1 to button 2, after the 2nd click?
these are my 2 button clicks</p>

```<code>private int lCount = 0;
private int rCount = 0;
private int myCount = lCount & rCount;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);

countButtonPlusL.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
             countTextViewPlusL.setBackgroundColor(0xffffffff);}
          else countTextViewPlusL.setBackgroundColor(0x00000000);
        lCount++;
        if (lCount >-1)
        countTextViewPlusL.setText("" + lCount);
    }
});

final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

countButtonPlusR.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
            countTextViewPlusR.setBackgroundColor(0xffffffff);}
          else countTextViewPlusR.setBackgroundColor(0x00000000);
        rCount++;
        if (rCount >-1)
        countTextViewPlusR.setText("" + rCount);
    }
});
</code>```

答:
Why don't you try something like this instead?

```<code>private int lCount = 0;
private int rCount = 0;
private int myCount = 0;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);
final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

View.OnClickListener listener = new View.OnClickListener() {
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.ButtonCountPlusR:
                rCount++;
                break;
            case R.id.ButtonCountPlusL:
                lCount++;
                break;
        }
        myCount = lCount + rCount;
        if(myCount % 2 == 0) {
            //invert colors here
        }
    }
});

countButtonPlusL.setOnClickListener(listener);
countButtonPlusR.setOnClickListener(listener);
</code>```

Initialize all counters to zero, then check on each click which button was clicked, increment its counter, set myCount equal to the sum of both left and right counters, then check if it's a second click. Inside that check, invert your TextView colors.

Title: color switch after the 2nd button click

Body:
how can i use the "switch statement" to switch the colors from button 1 to button 2, after the 2nd click?
these are my 2 button clicks

private int lCount = 0;
private int rCount = 0;
private int myCount = lCount & rCount;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);

countButtonPlusL.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
             countTextViewPlusL.setBackgroundColor(0xffffffff);}
          else countTextViewPlusL.setBackgroundColor(0x00000000);
        lCount++;
        if (lCount >-1)
        countTextViewPlusL.setText("" + lCount);
    }
});

final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

countButtonPlusR.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
            countTextViewPlusR.setBackgroundColor(0xffffffff);}
          else countTextViewPlusR.setBackgroundColor(0x00000000);
        rCount++;
        if (rCount >-1)
        countTextViewPlusR.setText("" + rCount);
    }
});

Body:
Why don't you try something like this instead?

private int lCount = 0;
private int rCount = 0;
private int myCount = 0;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);
final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

View.OnClickListener listener = new View.OnClickListener() {
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.ButtonCountPlusR:
                rCount++;
                break;
            case R.id.ButtonCountPlusL:
                lCount++;
                break;
        }
        myCount = lCount + rCount;
        if(myCount % 2 == 0) {
            //invert colors here
        }
    }
});

countButtonPlusL.setOnClickListener(listener);
countButtonPlusR.setOnClickListener(listener);

Initialize all counters to zero, then check on each click which button was clicked, increment its counter, set myCount equal to the sum of both left and right counters, then check if it's a second click. Inside that check, invert your TextView colors.


问:
Debugging VisualVM remote connection
I am running Tomcat 6 on a Linux server in Amazon's cloud.  I am trying to connect to it with VisualVM from my Mac at my office.  I have allowed opened up all TCP ports between my desktop and the server, but I am unable to get VisualVM to do anything.

On the linux box, I have started Tomcat with:

```<code>-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9191
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
</code>```

On my Mac, I launch VisualVM and choose File -> New JMX Connection...

I enter amazonhostname.com:9191 in the box.  It says "Adding amazonhostname.com:9191..." and sits there for several minutes before timing out.

From my Mac, I can "telnet amazonhostname.com 9191" just fine, and I tried some other random ports, and they all worked.  I'm pretty convinced it's not a firewall issue, unless I need to open UDP or ICMP or something like that.  (Really??)

There is nothing in catalina.log on the server, or the system console on my Mac, related to jmx.  netstat on the server shows 9191 and some other ports open on all interfaces.

There is no jstatd on the remote server.  Is that a pre-requisite for JMX?  (I am totally new to Java and I'm not even sure what those things mean, but I saw it on a blog post somewhere.  I'm grasping at straws now.)

答:
What worked well for me in RHEL7 environment is to implement the JmxRemoteLifecycleListener on Tomcat using the example provided in the documentation. I have also opened up ports 10001 and 10002 on the firewall.
JMX Remote Lifecycle Listener</p>

Title: Debugging VisualVM remote connection

Body:
I am running Tomcat 6 on a Linux server in Amazon's cloud.  I am trying to connect to it with VisualVM from my Mac at my office.  I have allowed opened up all TCP ports between my desktop and the server, but I am unable to get VisualVM to do anything.

On the linux box, I have started Tomcat with:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9191
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false

On my Mac, I launch VisualVM and choose File -> New JMX Connection...

I enter amazonhostname.com:9191 in the box.  It says "Adding amazonhostname.com:9191..." and sits there for several minutes before timing out.

From my Mac, I can "telnet amazonhostname.com 9191" just fine, and I tried some other random ports, and they all worked.  I'm pretty convinced it's not a firewall issue, unless I need to open UDP or ICMP or something like that.  (Really??)

There is nothing in catalina.log on the server, or the system console on my Mac, related to jmx.  netstat on the server shows 9191 and some other ports open on all interfaces.

There is no jstatd on the remote server.  Is that a pre-requisite for JMX?  (I am totally new to Java and I'm not even sure what those things mean, but I saw it on a blog post somewhere.  I'm grasping at straws now.)


问:
When using csv.writer to write a specific column to a new file, the loop is iterating over every character
Ok, so I am new to programming in general and absolutely new to Python. I'm starting to build my first project which basically will go get CSV files of state data and then pull from each file to create a single file. Anyway, to start I want to just get it to work with one file.

```<code>import csv

with open('Active_Iowa_Business_Entities.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    with open('new_names_now.csv', 'w') as new_file:
        csv_writer = csv.writer(new_file)

        for line in csv_reader:
            csv_writer.writerow(str(line[2]))
</code>```

My problem is, while I have figured out how to get the specific column I want the loop seems to be iterating over each letter in that column. So instead of getting this:

REVISED DOMESTIC NON-PROFIT

I am getting this:

R,E,V,I,S,E,D, ,D,O,M,E,S,T,I,C, ,N,O,N,-,P,R,O,F,I,T

What am I doing wrong?

答:
csv.writer.writerow takes an iterable as argument, where each element of the iterable is a value you want to write in your line, so here, you'd write:

```<code>csv_writer.writerow((str(line[2]),))
</code>```

Where (str(line[2]),) is a tuple containing only the element you want to write.

Body:
Ok, so I am new to programming in general and absolutely new to Python. I'm starting to build my first project which basically will go get CSV files of state data and then pull from each file to create a single file. Anyway, to start I want to just get it to work with one file.

import csv

with open('Active_Iowa_Business_Entities.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    with open('new_names_now.csv', 'w') as new_file:
        csv_writer = csv.writer(new_file)

        for line in csv_reader:
            csv_writer.writerow(str(line[2]))

My problem is, while I have figured out how to get the specific column I want the loop seems to be iterating over each letter in that column. So instead of getting this:

REVISED DOMESTIC NON-PROFIT

I am getting this:

R,E,V,I,S,E,D, ,D,O,M,E,S,T,I,C, ,N,O,N,-,P,R,O,F,I,T

What am I doing wrong?

Body:
csv.writer.writerow takes an iterable as argument, where each element of the iterable is a value you want to write in your line, so here, you'd write:

csv_writer.writerow((str(line[2]),))

Where (str(line[2]),) is a tuple containing only the element you want to write.


问:
Part of text dose not show up on screen. JavaScript beginner
Ending screen should show winning player and sign "click to continue" which is doing but only with the click to continue. I just start with javascript and i try to write code as logic as i can.

```<code>function drawEverything() {

canvasContext.fillStyle = 'black';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);

if (showWinScreen) {
  canvasContext.fillStyle = 'white';
  if (player1Score >= WINNING_SCORE) {
    canvasContext.fillText("PLAYER 1 WON!", 400, 100);
  } else if (player2Score >= WINNING_SCORE) {
    canvasContext.fillText("PLAYER 2 WON!", 400, 100);
  }

  canvasContext.fillText("PLEASE CLICK TO CONTINUE", 350, 500);
  return;
}
</code>```

Variables from this code below are now changed to the part which is last in sequence of work.

```<code>function ballReset() {
if (player1Score >= WINNING_SCORE ||
  player2Score >= WINNING_SCORE) {
  player1Score = 0;
  player2Score = 0;
  showWinScreen = true;
}
</code>```

Now they are here on part that is closing screen with information which shows who won but problem is still same :/

```<code>function mouseClick(evt) {
player1Score = 0;
player2Score = 0;
showWinScreen = false;
</code>```

}

答: You only draw the victory message if (player1Score >= WINNING_SCORE). However, player1Score gets set to zero in ballReset(), so it can't possibly be greater than the WINNING_SCORE. You need to store the winning player some other way or don't reset the scores to zero until the game restarts.

Body:
Ending screen should show winning player and sign "click to continue" which is doing but only with the click to continue. I just start with javascript and i try to write code as logic as i can.

function drawEverything() {

canvasContext.fillStyle = 'black';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);

if (showWinScreen) {
  canvasContext.fillStyle = 'white';
  if (player1Score >= WINNING_SCORE) {
    canvasContext.fillText("PLAYER 1 WON!", 400, 100);
  } else if (player2Score >= WINNING_SCORE) {
    canvasContext.fillText("PLAYER 2 WON!", 400, 100);
  }

  canvasContext.fillText("PLEASE CLICK TO CONTINUE", 350, 500);
  return;
}

Variables from this code below are now changed to the part which is last in sequence of work.

function ballReset() {
if (player1Score >= WINNING_SCORE ||
  player2Score >= WINNING_SCORE) {
  player1Score = 0;
  player2Score = 0;
  showWinScreen = true;
}

Now they are here on part that is closing screen with information which shows who won but problem is still same :/

function mouseClick(evt) {
player1Score = 0;
player2Score = 0;
showWinScreen = false;

}


问:
If I were to build a new operating system, what kind of features would it have?
I am toying with the idea of creating an completely new operating system and would like to hear what everyone on this forums take is on that?  First is it too late are the big boys so entrenched in our lives that we will never be able to switch (wow - what a terrible thought...).  But if this is not the case, what should a operating system do for you? What features are the most important?  Should all the components be separate installations (in other words - should the base OS really have no user functionality and that gets added on by creating "plug-ins" kind of like a good flexible tool?)

Why do I want to do this...  I am more curious about whether there is a demand and I am wondering, since the OSes we use most today (Linux, Windows, Mac OS X (Free BSD)) were actually written more than 20 years ago (and I am being generous - I mean dual and quad cores did not exist back then, buses were much slower, hardware was much more expensive, etc,...),  I was just curious with the new technology if we would do anything differently?

I am anxious to read your comments.

答:
If you're asking what I'd like to see in an operating system, I can give you a list.  I am just getting into programming so I'm not sure if any of this is possible, but I can give you my ideas.

I'd like to see a developed operating system (besides the main ones) in which it ISN'T a pain to get the wireless card to work.  That is my #1 pet peeve with most of the ones I've tried out.

It would be cool to see an operating system designed by a programmer for other programmers.  Have it so you can run programs for all different operating systems.  I don't know if that's possible without having a copy of windows and OSX but it would be really damn cool if I could check the compatablity of programs I write with all operating systems.

OwnerDisplayName: Autobyte

LastEditorDisplayName: Juan Manuel


问:
What do delegates catch with a parent and embedded view controller?
I have a view controller (VC1) which has a container view that holds a table view/VC2.

How I can catch things like scrolling in table view (VC2) but from VC1? Can I use delegates?

Also I am implementing a search feature. Do I have to update the embedded VC2 from VC1, is that also done using delegates?

答:
Now I wonder how I can catch things like scrolling in VC2/table view
  but from VC1?

You can catch scrolling in the same VC (in your case VC2), then relay that information to VC1 via custom protocols and delegates.

General principle: You should treat embedded view controllers like any view controller.

For example, when you want to pass data to the parent view controller from the embedded view controller you could relay that via delegates. You would use the prepeForSegue method to set the parent view controller as the delegate.

Similarly, when you want to pass data from the parent view controller to the embedded view controller, you can again pass it via the prepareForSegue method. This time you set data from the parent view controller to an embedded view controller variable.

These principles are true for passing data and delegating responsibility to other view controllers, and embedded view controllers should be treated the same way.


问:
Taking the last five digits of a number from user input in REACT.jsx
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

```<code>{this.props.x ? (
              <p>
                Card number: <br />
                {"***** *****" + this.props.x}
              </p>
            ) : (
              ""
            )
</code>```

I want the end result to look like
***** ***** 54321

答:
Maybe try turning into a string so you can use the substr method.

```<code>const string = this.props.x.toString()
const lastFive = string.substr(string.length - 5);
</code>```

Hope this helps.

Body:
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

{this.props.x ? (

                Card number:

                {"***** *****" + this.props.x}

            ) : (
              ""
            )

I want the end result to look like
***** ***** 54321

Body:
Maybe try turning into a string so you can use the substr method.

const string = this.props.x.toString()
const lastFive = string.substr(string.length - 5);

Hope this helps.


问:
how to calculate total amount of Jenkin's jobs
in our working Jenkins there are hundreds executing jobs. And I'm interesting does Jenkins store somewhere total number of jobs which are currently executing or I should manually calculate it one by one?</p>

答:
i´m triying to use this plugin also.
It´s easy to install and configure. All in Configure System.
For example in my screen/case, put this:

$N1: $T pipelines, $S Ok, $F Failed, $U Unstable, $D DIsabled


问:
How to rotate axes titles in matplotlib?
I'm unable to rotate the names on both the y and x axes such that they overlap. What am I doing wrong?

yticks/xticks(rotation=90) also does not adjust the names to prevent them from overlapping.

```<code>name = 'Anne Frank Diary'
df4 = df.loc[ my_list, my_list ].copy()
axes = pd.plotting.scatter_matrix(df4, figsize=(15, 15), marker='o',hist_kwds={'bins': 20}, s=60, alpha=.8)
corr = df4.corr().values
for i, j in zip(*plt.np.triu_indices_from(axes, k=1)):
    axes[i, j].annotate("%.3f" %corr[i,j], (0.8, 0.8), xycoords='axes fraction', ha='left', va='center',rotation=90)
sst="%s \n Scatter Matrix of Centrality Indices \n (displaying Pearson correlation coefficients)" %name
plt.suptitle(sst,fontsize=20);
</code>```

Update:
https://github.com/markamcgown/Projects/blob/master/df.csv
my_list = ['Kugler',
 'Margot',
 'Anne',
 'Pirn',
 'Kleiman',
 'German',
 'Dutch',
 'Dussel',
 'Annex',
 'Peter',
 'Kitty',
 'Bep',
 'Mouschi',
 'British',
 'Miep',
 'van D.']

答:
```<code>n = len(G.nodes)

for x in range(n):
    for y in range(n):
        # to get the axis of subplots
        ax = axes[x, y]
        # to make x axis name vertical
        ax.xaxis.label.set_rotation(90)
        # to make y axis name horizontal
        ax.yaxis.label.set_rotation(0)
        # to make sure y axis names are outside the plot area
        ax.yaxis.labelpad = 10
``
</code>```

Body:
I'm unable to rotate the names on both the y and x axes such that they overlap. What am I doing wrong?

yticks/xticks(rotation=90) also does not adjust the names to prevent them from overlapping.

name = 'Anne Frank Diary'
df4 = df.loc[ my_list, my_list ].copy()
axes = pd.plotting.scatter_matrix(df4, figsize=(15, 15), marker='o',hist_kwds={'bins': 20}, s=60, alpha=.8)
corr = df4.corr().values
for i, j in zip(*plt.np.triu_indices_from(axes, k=1)):
    axes[i, j].annotate("%.3f" %corr[i,j], (0.8, 0.8), xycoords='axes fraction', ha='left', va='center',rotation=90)
sst="%s \n Scatter Matrix of Centrality Indices \n (displaying Pearson correlation coefficients)" %name
plt.suptitle(sst,fontsize=20);

Update:
https://github.com/markamcgown/Projects/blob/master/df.csv
my_list = ['Kugler',
 'Margot',
 'Anne',
 'Pirn',
 'Kleiman',
 'German',
 'Dutch',
 'Dussel',
 'Annex',
 'Peter',
 'Kitty',
 'Bep',
 'Mouschi',
 'British',
 'Miep',
 'van D.']


问:
Perform an operation on multiple tables in a list
Trying to teach myself Power Query and can't get my head around this particular process.

I understand there may be other, perhaps more efficient methods of attaining the desired result, but my purpose here is to understand the process of performing multiple operations on each table in a list of tables, where the number of entries in the list is unknown and/or large.

My original data has pairs of information [Credit, Name] in adjacent columns with an unknown number of pairs.

Since it is a table, the different column/pairs have different Names.

Credit|Name|Credit1|Name1|...

If I demote the headers and transpose the table, the column headers will wind up in Column 1, and I can strip off the differentiating digit.

Using Table.Split, I can then create a number of tables where each pair of columns has the Identical headers.

I can then combine these tables to create a single, two column table, where I can Group and aggregate to get the results.

My problem is that I have not been able to figure out how to do the:

```<code>Table.PromoteHeaders(Table.Transpose(table))
</code>```

operation on each table.

This M-code produces the desired result for the four pairs of columns in the provided data, but is clearly not scalable since the number of tables needs to be known in advance.

```<code>let
   //Create the table
   Tbl1= Table.FromRecords({
      [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
      [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"]
      }),

   //Demote headers and transpose
   transpose1 = Table.Transpose( Table.DemoteHeaders(Tbl1)),

   //Create matching names for what will eventually be the final Column Headers
    #"Split Column by Character Transition" = Table.SplitColumn(transpose1, "Column1", Splitter.SplitTextByCharacterTransition((c) => not List.Contains({"0".."9"}, c), {"0".."9"}), {"Column1.1", "Column1.2"}),
    #"Removed Columns" = Table.RemoveColumns(#"Split Column by Character Transition",{"Column1.2"}),

   //Create multiple tables from above
    multTables = Table.Split(#"Removed Columns",2),

   /*transpose and promote the headers for each table
   HOW can I do this in a single step when I don't know how many tables there might be???
   */

   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
    combTable
</code>```

Original Table

Demoted headers / Transposed table

Desired Result

Any help would be appreciated.

答:
You could also try replacing this part of your code:

```<code>   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
   combTable
</code>```

with this:

```<code>    Custom1 = List.Transform(multTables, each Table.PromoteHeaders( Table.Transpose(_),[PromoteAllScalars=true])),
    #"Converted to Table" = Table.FromList(Custom1, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Expanded Column1" = Table.ExpandTableColumn(#"Converted to Table", "Column1", {"Credit", "Name"}, {"Credit", "Name"})
in
    #"Expanded Column1"
</code>```

Body:
Trying to teach myself Power Query and can't get my head around this particular process.

I understand there may be other, perhaps more efficient methods of attaining the desired result, but my purpose here is to understand the process of performing multiple operations on each table in a list of tables, where the number of entries in the list is unknown and/or large.

My original data has pairs of information [Credit, Name] in adjacent columns with an unknown number of pairs.

Since it is a table, the different column/pairs have different Names.

Credit|Name|Credit1|Name1|...

If I demote the headers and transpose the table, the column headers will wind up in Column 1, and I can strip off the differentiating digit.

Using Table.Split, I can then create a number of tables where each pair of columns has the Identical headers.

I can then combine these tables to create a single, two column table, where I can Group and aggregate to get the results.

My problem is that I have not been able to figure out how to do the:

Table.PromoteHeaders(Table.Transpose(table))

operation on each table.

This M-code produces the desired result for the four pairs of columns in the provided data, but is clearly not scalable since the number of tables needs to be known in advance.

let
   //Create the table
   Tbl1= Table.FromRecords({
      [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
      [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"]
      }),

   //Demote headers and transpose
   transpose1 = Table.Transpose( Table.DemoteHeaders(Tbl1)),

   //Create matching names for what will eventually be the final Column Headers
    #"Split Column by Character Transition" = Table.SplitColumn(transpose1, "Column1", Splitter.SplitTextByCharacterTransition((c) => not List.Contains({"0".."9"}, c), {"0".."9"}), {"Column1.1", "Column1.2"}),
    #"Removed Columns" = Table.RemoveColumns(#"Split Column by Character Transition",{"Column1.2"}),

   //Create multiple tables from above
    multTables = Table.Split(#"Removed Columns",2),

   /*transpose and promote the headers for each table
   HOW can I do this in a single step when I don't know how many tables there might be???
   */

   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
    combTable

Original Table

Demoted headers / Transposed table

Desired Result

Any help would be appreciated.

Body:
You could also try replacing this part of your code:

   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
   combTable

with this:

    Custom1 = List.Transform(multTables, each Table.PromoteHeaders( Table.Transpose(_),[PromoteAllScalars=true])),
    #"Converted to Table" = Table.FromList(Custom1, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Expanded Column1" = Table.ExpandTableColumn(#"Converted to Table", "Column1", {"Credit", "Name"}, {"Credit", "Name"})
in
    #"Expanded Column1"


问:
How do I get the directory where a Bash script is located from within the script itself?
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

```<code>$ ./application
</code>```

答:
I don't think this is as easy as others have made it out to be.  pwd doesn't work, as the current directory is not necessarily the directory with the script.  $0 doesn't always have the information either.  Consider the following three ways to invoke a script:

```<code>./script

/usr/bin/script

script
</code>```

In the first and third ways $0 doesn't have the full path information.  In the second and third, pwd does not work.  The only way to get the directory in the third way would be to run through the path and find the file with the correct match.  Basically the code would have to redo what the OS does.

One way to do what you are asking would be to just hardcode the data in the /usr/share directory, and reference it by its full path.  Data shoudn't be in the /usr/bin directory anyway, so this is probably the thing to do.

OwnerDisplayName: Jim Robert

Body:
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Body:
I don't think this is as easy as others have made it out to be.  pwd doesn't work, as the current directory is not necessarily the directory with the script.  $0 doesn't always have the information either.  Consider the following three ways to invoke a script:

./script

/usr/bin/script

script

In the first and third ways $0 doesn't have the full path information.  In the second and third, pwd does not work.  The only way to get the directory in the third way would be to run through the path and find the file with the correct match.  Basically the code would have to redo what the OS does.

One way to do what you are asking would be to just hardcode the data in the /usr/share directory, and reference it by its full path.  Data shoudn't be in the /usr/bin directory anyway, so this is probably the thing to do.

OwnerDisplayName: Jim


问:
Double spacing lines in a Linux terminal
Does anyone know if it's possible to force terminal to append a \n to every line it prints (or something similar)?

I'm trying to debug some insane code which gives me errors the full width of my (24") screen and three lines long, so I'd appreciate not having to copy things into gedit and manually spacing them out every time I press make.

Cheers, Ed

N.B. I'm using "make 2>&1 | more" so I can't just do "| sed G"

(EDITED for clarity)

答:
If you want to change this on the entire terminal, you append '\n' to the PS1 variable in your .bash_rc file.

For instance:

```<code>PS1 = '\n> '
</code>```

**EDIT:**This will put newlines between commands you enter on the command prompt but won't affect the output of applications.

OwnerDisplayName: Ed Woodcock

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ed Woodcock

Body:
If you want to change this on the entire terminal, you append '\n' to the PS1 variable in your .bash_rc file.

For instance:

PS1 = '\n> '

**EDIT:**This will put newlines between commands you enter on the command prompt but won't affect the output of applications.


问:
Too Many DOM Elements
I am building a one page webapp and it's starting to get pretty big. There are several components to the app, each one meticulously styled. On average the app has a DOM element count of 1200+. I have been warned by my YSlow scan that this is too many, and that I should have no more than 700 DOM elements.

I am usually quite strict and efficient with my markup and I doubt I would be able to trim much off. I tend to use a lot of DOM elements to get the styling exactly right and working cross browser.

How can I dramatically cut the number of DOM elements?
Will I have to load more of the content on demand (ajax) instead on all on page load?
Does a large amount of DOM elements have a big impact on performance?

I would love to hear people's experience with this and any solutions you may have...

答:
How can I dramatically cut the number of DOM elements?

By using only those elements that are necessary. If you want an more elaborate advice, post your code.

Will I have to load more of the content on demand (ajax) instead on all on page load?

If you want your page to perform better on start-up, you can do that.

Does a large amount of DOM elements have a big impact on performance?

Not necessarily.

Title: Too Many DOM Elements


问:
Why does date_range give a result different from indexing [] for DataFrame Pandas dates?
Here is a simple code with date_range and indexing [ ] I used with Pandas

```<code>period_start = '2013-01-01'
period_end = '2019-12-24'

print(pd.DataFrame ({'close':aapl_close,
        'returns':aapl_returns},index=pd.date_range(start=period_start,periods=6)))

print(pd.DataFrame ({'close':aapl_close,
            'returns':aapl_returns})[period_start:'20130110'])
</code>```

date_range gives Nan results

```<code>            close  returns
2013-01-01    NaN      NaN
2013-01-02    NaN      NaN
2013-01-03    NaN      NaN
2013-01-04    NaN      NaN
</code>```

Indexing gives correct results

```<code>                            close   returns
2013-01-02 00:00:00+00:00  68.732  0.028322
2013-01-03 00:00:00+00:00  68.032 -0.010184
2013-01-04 00:00:00+00:00  66.091 -0.028531
</code>```

Based on how the dates are shown by date_range - I suppose the date format of date_range does not match the date format in the Pandas DataFrame.

1) Can you explaine please why it gives NaN?

2) What would you suggest to get a specific time range from the Panda DataFrame?

答:
As I'm a beginner in Python and its libraries, I didn't understand that this question refers to the Quantopian library, not to Pandas.

I got a solution on their forum. All the times returned by methods on Quantopian are timezone aware with a timezone of 'UTC'. By default, the date_range method returns timezone naive dates. Simply supply the timezone information to date_range method. Like this

```<code>pd.DataFrame ({
'close':aapl_close,
'returns':aapl_returns,},
index=pd.date_range(start=period_start, periods=6, tz='UTC'))
</code>```

To get a specific date or time range in pandas perhaps the easiest is simple bracket notation. For example, to get dates between 2013-01-04 and 2013-01-08 (inclusive) simply enter this:

```<code>df = pd.DataFrame ({'close':aapl_close,  'returns':aapl_returns,})
my_selected_dates = df['2013-01-04':'2013-01-08']
</code>```

This bracket notation is really shorthand for using the loc method

```<code>my_selected_dates = df.loc['2013-01-04':'2013-01-08']
</code>```

Both work the same but the loc method has a bit more flexibility. This notation also works with datetimes if desired.

Body:
Here is a simple code with date_range and indexing [ ] I used with Pandas

period_start = '2013-01-01'
period_end = '2019-12-24'

print(pd.DataFrame ({'close':aapl_close,
        'returns':aapl_returns},index=pd.date_range(start=period_start,periods=6)))

print(pd.DataFrame ({'close':aapl_close,
            'returns':aapl_returns})[period_start:'20130110'])

date_range gives Nan results

            close  returns
2013-01-01    NaN      NaN
2013-01-02    NaN      NaN
2013-01-03    NaN      NaN
2013-01-04    NaN      NaN

Indexing gives correct results

                            close   returns
2013-01-02 00:00:00+00:00  68.732  0.028322
2013-01-03 00:00:00+00:00  68.032 -0.010184
2013-01-04 00:00:00+00:00  66.091 -0.028531

Based on how the dates are shown by date_range - I suppose the date format of date_range does not match the date format in the Pandas DataFrame.

1) Can you explaine please why it gives NaN?

2) What would you suggest to get a specific time range from the Panda DataFrame?

Body:
As I'm a beginner in Python and its libraries, I didn't understand that this question refers to the Quantopian library, not to Pandas.

I got a solution on their forum. All the times returned by methods on Quantopian are timezone aware with a timezone of 'UTC'. By default, the date_range method returns timezone naive dates. Simply supply the timezone information to date_range method. Like this

pd.DataFrame ({
'close':aapl_close,
'returns':aapl_returns,},
index=pd.date_range(start=period_start, periods=6, tz='UTC'))

To get a specific date or time range in pandas perhaps the easiest is simple bracket notation. For example, to get dates between 2013-01-04 and 2013-01-08 (inclusive) simply enter this:

df = pd.DataFrame ({'close':aapl_close,  'returns':aapl_returns,})
my_selected_dates = df['2013-01-04':'2013-01-08']

This bracket notation is really shorthand for using the loc method

my_selected_dates = df.loc['2013-01-04':'2013-01-08']

Both work the same but the loc method has a bit more flexibility. This notation also works with datetimes if desired.


问:
Calendar and array list : how do I assign the date right?
below the lastDay variable does not always contain the i+1 of the list. No clue why.
I am in the course of introducing the Date from Java 8. But still I would like to know what is going wrong...
Peter (very beginner)

```<code>// organize the intervals and split them into the years
        ArrayList<intervall> tmpIntervallList = new ArrayList<intervall>();
        Calendar lastDay = Calendar.getInstance();

        for (i = 0; i < deliveryList.size() - 1; i++) {

            Log.d(TAG, "my log comments: Intervallanfang " +
                    deliveryList.get(i).getDatumasString() +" nächstes: " + deliveryList.get(i+1).getDatumasString());
            //Beginning of the next intervall -1 is the last day of the Intervall before.
            lastDay.set(deliveryList.get(i+1).getYear(),
                    deliveryList.get(i+1).getMonth(),
                    deliveryList.get(i+1).getDay());

            //debugging
            String tmp1String = String.format("%d/%d/%d", lastDay.get(Calendar.DAY_OF_MONTH),
                    lastDay.get(Calendar.MONTH) + 1,
                    lastDay.get(Calendar.YEAR));
            Log.d(TAG, "my log comments: tmp lastday " + tmp1String );

            lastDay.add(Calendar.DATE, -1);

            //debugging
            String tmpString = String.format("%d/%d/%d", lastDay.get(Calendar.DAY_OF_MONTH),
                    lastDay.get(Calendar.MONTH) + 1,
                    lastDay.get(Calendar.YEAR));
            Log.d(TAG, "my log comments: ende intervall " + tmpString);

            intervall tmp2intervall = new intervall(deliveryList.get(i).getAmountFilled(),
                    deliveryList.get(i).getYear(),
                    deliveryList.get(i).getMonth(),
                    deliveryList.get(i).getDay(),
                    lastDay.get(Calendar.YEAR),
                    lastDay.get(Calendar.MONTH),
                    lastDay.get(Calendar.DAY_OF_MONTH));
            tmpIntervallList.add(tmp2intervall);
        }
</code>```

And the outcome is

my log comments: Intervallanfang 01/01/2018 nächstes: 01/02/2018

my log comments: tmp lastday 1/1/2018

my log comments: ende intervall 31/12/2017

my log comments: Intervallanfang 01/02/2018 nächstes: 01/06/2018

my log comments: tmp lastday 1/1/2018

my log comments: ende intervall 31/12/2017

my log comments: Intervallanfang 01/06/2018 nächstes: 01/01/2019

my log comments: tmp lastday 1/1/2019

my log comments: ende intervall 31/12/2018

my log comments: Intervallanfang 01/01/2019 nächstes: 01/01/2020

my log comments: tmp lastday 1/1/2020

my log comments: ende intervall 31/12/2019

my log comments: Intervallanfang 01/01/2020 nächstes: 01/06/2020

my log comments: tmp lastday 1/1/2020

my log comments: ende intervall 31/12/2019

my log comments: Intervallanfang 01/06/2020 nächstes: 02/01/2021

my log comments: tmp lastday 2/1/2021

my log comments: ende intervall 1/1/2021

as requested some more source code

```<code>    public  intervall(int amountFilled, int yearBegin, int monthBegin, int
               dayBegin, int yearEnd, int monthEnd, int dayEnd) {
                   begin = Calendar.getInstance();
                   end = Calendar.getInstance();
                   this.setIntervall( yearBegin, monthBegin, dayBegin,
                          yearEnd, monthEnd, dayEnd);
                   this.amountFilled = amountFilled;
</code>```

....

```<code>    public void setIntervall(int amountFilled, int yearBegin, int
    monthBegin, int dayBegin, int yearEnd, int monthEnd, int dayEnd){
       this.begin.set(yearBegin, monthBegin, dayBegin);
       this.end.set(yearEnd, monthEnd, dayEnd);
</code>```

.....

答:
this does not explain the strange behavior. As written I am in the
course of introducing the Date from Java 8 but still I would like to
understand.

Let’s just inspect the first two lines of your log output for a start:

```<code>my log comments: Intervallanfang 01/01/2018 nächstes: 01/02/2018
my log comments: tmp lastday 1/1/2018
</code>```

(For readers who don’t read German: the first line means interval start 01/01/2018 next: 01/02/2018.)

The dates nächstes and tmp lastday come from the same element from your deliveryList, namely deliveryList.get(i+1). 01/02/2018 comes from getDatumasString() whereas 1/1/2018 comes from getYear(), getMonth() and getDay(). In the output you have correctly added 1 to the month number because the months are insanely numbered from 0 instead of 1 (probably a trait from the confusing GregorianCalendar class). So when these two dates do not agree, the problem must be inside whatever class those deliveries belong to. With the information you have provided, I don’t know what class that is, and even less what the problem in that class is (there was a reason why in a comment I encouraged you to create a Minimal, Reproducible Example).

There is a pattern, though: When we read your entire log output, nächstes and tmp lastday always agree on year and on day of month (even in the last iteration, where day of month is 2 for a change). And tmp lastday always gives month as 1 (January) no matter what it is in nächstes (2, 6 or 1). So it would seem that there’s a bug in getMonth() that causes it to return 0 (January) always irrespective of what is in the object.

Why getMonth() always returns January, it’s guesswork from me, but I dare start guessing. It might come from parsing the date string using SimpleDateFormat, a notorious troublemaker of a class. There are two typical errors that regularly causes it to return a date in January even though the input string is in a different month:

Using upper case Y instead of lower case y for year in a format pattern string. See for example java parsing string to date.

Even more likely in your case, using lower case m for month. See for example SimpleDateFormat ignoring month when parsing

If any of these two turns out to fit your issue, I can almost guarantee you one thing: It would not have happened with java.time, the modern Java date and time API that Basil Bourque rightfully endorses in the other answer. java.time much better catches such errors long before you need to start debugging them.

Body:
below the lastDay variable does not always contain the i+1 of the list. No clue why.
I am in the course of introducing the Date from Java 8. But still I would like to know what is going wrong...
Peter (very beginner)

// organize the intervals and split them into the years
        ArrayList<intervall> tmpIntervallList = new ArrayList<intervall>();
        Calendar lastDay = Calendar.getInstance();

        for (i = 0; i < deliveryList.size() - 1; i++) {

            Log.d(TAG, "my log comments: Intervallanfang " +
                    deliveryList.get(i).getDatumasString() +" nächstes: " + deliveryList.get(i+1).getDatumasString());
            //Beginning of the next intervall -1 is the last day of the Intervall before.
            lastDay.set(deliveryList.get(i+1).getYear(),
                    deliveryList.get(i+1).getMonth(),
                    deliveryList.get(i+1).getDay());

            //debugging
            String tmp1String = String.format("%d/%d/%d", lastDay.get(Calendar.DAY_OF_MONTH),
                    lastDay.get(Calendar.MONTH) + 1,
                    lastDay.get(Calendar.YEAR));
            Log.d(TAG, "my log comments: tmp lastday " + tmp1String );

            lastDay.add(Calendar.DATE, -1);

            //debugging
            String tmpString = String.format("%d/%d/%d", lastDay.get(Calendar.DAY_OF_MONTH),
                    lastDay.get(Calendar.MONTH) + 1,
                    lastDay.get(Calendar.YEAR));
            Log.d(TAG, "my log comments: ende intervall " + tmpString);

            intervall tmp2intervall = new intervall(deliveryList.get(i).getAmountFilled(),
                    deliveryList.get(i).getYear(),
                    deliveryList.get(i).getMonth(),
                    deliveryList.get(i).getDay(),
                    lastDay.get(Calendar.YEAR),
                    lastDay.get(Calendar.MONTH),
                    lastDay.get(Calendar.DAY_OF_MONTH));
            tmpIntervallList.add(tmp2intervall);
        }

And the outcome is

my log comments: Intervallanfang 01/01/2018 nächstes: 01/02/2018

my log comments: tmp lastday 1/1/2018

my log comments: ende intervall 31/12/2017

my log comments: Intervallanfang 01/02/2018 nächstes: 01/06/2018

my log comments: tmp lastday 1/1/2018

my log comments: ende intervall 31/12/2017

my log comments: Intervallanfang 01/06/2018 nächstes: 01/01/2019

my log comments: tmp lastday 1/1/2019

my log comments: ende intervall 31/12/2018

my log comments: Intervallanfang 01/01/2019 nächstes: 01/01/2020

my log comments: tmp lastday 1/1/2020

my log comments: ende intervall 31/12/2019

my log comments: Intervallanfang 01/01/2020 nächstes: 01/06/2020

my log comments: tmp lastday 1/1/2020

my log comments: ende intervall 31/12/2019

my log comments: Intervallanfang 01/06/2020 nächstes: 02/01/2021

my log comments: tmp lastday 2/1/2021

my log comments: ende intervall 1/1/2021

as requested some more source code

    public  intervall(int amountFilled, int yearBegin, int monthBegin, int
               dayBegin, int yearEnd, int monthEnd, int dayEnd) {
                   begin = Calendar.getInstance();
                   end = Calendar.getInstance();
                   this.setIntervall( yearBegin, monthBegin, dayBegin,
                          yearEnd, monthEnd, dayEnd);
                   this.amountFilled = amountFilled;

....

    public void setIntervall(int amountFilled, int yearBegin, int
    monthBegin, int dayBegin, int yearEnd, int monthEnd, int dayEnd){
       this.begin.set(yearBegin, monthBegin, dayBegin);
       this.end.set(yearEnd, monthEnd, dayEnd);

.....

Body:
this does not explain the strange behavior. As written I am in the
course of introducing the Date from Java 8 but still I would like to
understand.

Let’s just inspect the first two lines of your log output for a start:

my log comments: Intervallanfang 01/01/2018 nächstes: 01/02/2018
my log comments: tmp lastday 1/1/2018

(For readers who don’t read German: the first line means interval start 01/01/2018 next: 01/02/2018.)

The dates nächstes and tmp lastday come from the same element from your deliveryList, namely deliveryList.get(i+1). 01/02/2018 comes from getDatumasString() whereas 1/1/2018 comes from getYear(), getMonth() and getDay(). In the output you have correctly added 1 to the month number because the months are insanely numbered from 0 instead of 1 (probably a trait from the confusing GregorianCalendar class). So when these two dates do not agree, the problem must be inside whatever class those deliveries belong to. With the information you have provided, I don’t know what class that is, and even less what the problem in that class is (there was a reason why in a comment I encouraged you to create a Minimal, Reproducible Example).

There is a pattern, though: When we read your entire log output, nächstes and tmp lastday always agree on year and on day of month (even in the last iteration, where day of month is 2 for a change). And tmp lastday always gives month as 1 (January) no matter what it is in nächstes (2, 6 or 1). So it would seem that there’s a bug in getMonth() that causes it to return 0 (January) always irrespective of what is in the object.

Why getMonth() always returns January, it’s guesswork from me, but I dare start guessing. It might come from parsing the date string using SimpleDateFormat, a notorious troublemaker of a class. There are two typical errors that regularly causes it to return a date in January even though the input string is in a different month:

Using upper case Y instead of lower case y for year in a format pattern string. See for example java parsing string to date.

Even more likely in your case, using lower case m for month. See for example SimpleDateFormat ignoring month when parsing

If any of these two turns out to fit your issue, I can almost guarantee you one thing: It would not have happened with java.time, the modern Java date and time API that Basil Bourque rightfully endorses in the other answer. java.time much better catches such errors long before you need to start debugging them.