问:
workstatus observer always in enqueued state
I am trying to observe my workers but they are always in queued state or sometime it's RUNNING but never SUCCEED or FAILED.

is workStatus.state from return in doWork() or it's different?

this is my worker script:

```<code>package com.mockie.daikokuten.sync.workers

import androidx.work.Worker

class TestWorker:Worker()
{

override fun doWork():Worker.Result
{
    return Worker.Result.SUCCESS
}

}
</code>```

this is script to observe the workers :

```<code> val test = PeriodicWorkRequest.Builder(
            TestWorker::class.java,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS)
            .addTag("test_worker")
            .build()

    WorkManager.getInstance()?.enqueueUniquePeriodicWork("test_worker", ExistingPeriodicWorkPolicy.KEEP, test)

    WorkManager.getInstance()!!.getStatusesByTag("test_worker")
            .observe(this, Observer { workStatus ->
                if (workStatus != null)
                {
                    for(ws in workStatus)
                    {
                        Log.d(":dump2 id ", ws.id.toString())
                        Log.d(":dump2 tag", ws.tags.toString())
                        Log.d(":dump2 state", ws.state.toString())
                    }
                }
            })
</code>```

this is the result in Logcat:

```<code> 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 id: 5c6297f7-11d8-4f2f-a327-773672a7435c
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 tag: [test_worker, com.mockie.daikokuten.sync.workers.TestWorker]
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 state: ENQUEUED
</code>```

答:
This is for anyone who is having trouble getting their output data from periodic work.
It's more like a hack.
In your Worker, just define a static mutable Live Data.
At the place where you observe your work's state, observe this live data when your state turns to "RUNNING".

Here's a template :

The actual Worker:

public class SomeWorker extends Worker{

   //This live data can be of any type. I'm setting Boolean
   Public static MutableLiveData<Boolean> outputObservable = new MutableLiveData();
   private boolean output_boolean;
   try{
       //Do you work here post your result to the live data
       output_boolean = SomeTaskThatReturnsABoolean();
       outputObservable.postValue(output_boolean);
       return Result.Success();
   }catch(Exception e){
       e.printStackTrace();
       outputObservable.postValue(!output_boolean);
       return Result.Failure();
    }
}

```

<ol start="2">
<li>Your activity that observes this worker's info:</li>
</ol>

<pre class="lang-java prettyprint-override"><code>//In YourActivity class inside OnCreate
mWorkManager.getWorkInfoForUniqueWorkLiveData(YOUR_TAG).observe (this,
   new Observer<List<WorkInfo>>(){
       @Override
       public void onChanged(@Nullable List<WorkInfo> workInfos) {
          if(workInfos!=null && (!(workInfos.isEmpty()))) {
             WorkInfo info = workInfos.get(0);
             switch(info.getState()){
               case ENQUEUED:
                   break;
               case RUNNING:
                   SomeWorker.outputObservable.observe(YourActivity.this,
                      new Observer<Boolean>(){
                      @Override
                       public void onChanged(@Nullable Boolean aBoolean) {
                           //EDIT: Remove the observer of the worker otherwise
                           //before execution of your below code, the observation might switch
                           mWorkManager.getWorkInfoForUniqueWorkLiveData(YOUR_TAG).removeObservers(YourActivity.this);
                           if(aBoolean)
                             //Do whatever you have to if it's true
                           else
                             //Do whatever you have to if it's false
                           }
                      }
                   );
             }
          }
       }
   }
);
</code>```

In this way you can observe your results when the state of the work is under running, before it gets switched back to enqueued.

Body:
I am trying to observe my workers but they are always in queued state or sometime it's RUNNING but never SUCCEED or FAILED.

is workStatus.state from return in doWork() or it's different?

this is my worker script:

package com.mockie.daikokuten.sync.workers

import androidx.work.Worker

class TestWorker:Worker()
{

override fun doWork():Worker.Result
{
    return Worker.Result.SUCCESS
}

}

this is script to observe the workers :

 val test = PeriodicWorkRequest.Builder(
            TestWorker::class.java,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS)
            .addTag("test_worker")
            .build()

    WorkManager.getInstance()?.enqueueUniquePeriodicWork("test_worker", ExistingPeriodicWorkPolicy.KEEP, test)

    WorkManager.getInstance()!!.getStatusesByTag("test_worker")
            .observe(this, Observer { workStatus ->
                if (workStatus != null)
                {
                    for(ws in workStatus)
                    {
                        Log.d(":dump2 id ", ws.id.toString())
                        Log.d(":dump2 tag", ws.tags.toString())
                        Log.d(":dump2 state", ws.state.toString())
                    }
                }
            })

this is the result in Logcat:

 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 id: 5c6297f7-11d8-4f2f-a327-773672a7435c
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 tag: [test_worker, com.mockie.daikokuten.sync.workers.TestWorker]
 07-23 17:12:30.901 29740-29740/com.mockie.daikokuten D/:dump2 state: ENQUEUED

Body:
This is for anyone who is having trouble getting their output data from periodic work.
It's more like a hack.
In your Worker, just define a static mutable Live Data.
At the place where you observe your work's state, observe this live data when your state turns to "RUNNING".

Here's a template :

The actual Worker:

public class SomeWorker extends Worker{

   //This live data can be of any type. I'm setting Boolean
   Public static MutableLiveData<Boolean> outputObservable = new MutableLiveData();
   private boolean output_boolean;
   try{
       //Do you work here post your result to the live data
       output_boolean = SomeTaskThatReturnsABoolean();
       outputObservable.postValue(output_boolean);
       return Result.Success();
   }catch(Exception e){
       e.printStackTrace();
       outputObservable.postValue(!output_boolean);
       return Result.Failure();
    }
}

Your activity that observes this worker's info:

//In YourActivity class inside OnCreate
mWorkManager.getWorkInfoForUniqueWorkLiveData(YOUR_TAG).observe (this,
   new Observer<List<WorkInfo>>(){
       @Override
       public void onChanged(@Nullable List<WorkInfo> workInfos) {
          if(workInfos!=null && (!(workInfos.isEmpty()))) {
             WorkInfo info = workInfos.get(0);
             switch(info.getState()){
               case ENQUEUED:
                   break;
               case RUNNING:
                   SomeWorker.outputObservable.observe(YourActivity.this,
                      new Observer<Boolean>(){
                      @Override
                       public void onChanged(@Nullable Boolean aBoolean) {
                           //EDIT: Remove the observer of the worker otherwise
                           //before execution of your below code, the observation might switch
                           mWorkManager.getWorkInfoForUniqueWorkLiveData(YOUR_TAG).removeObservers(YourActivity.this);
                           if(aBoolean)
                             //Do whatever you have to if it's true
                           else
                             //Do whatever you have to if it's false
                           }
                      }
                   );
             }
          }
       }
   }
);

In this way you can observe your results when the state of the work is under running, before it gets switched back to enqueued.


来源: stackexchange

问:
CSS Height:100% issue
I'm trying to get the div wrapper to surround all the divs within it so depending on the amount of content the height of wrapper will grow.

I guessed that the way of doing this would be to set height: 100% but as you can see from the screen grab below, this is not the case.

Where it says 'No :-(' is what having height: 100% is doing where ideally I would like wrapper to be at the bottom where it says 'Yes' and I have drawn a red line.

Any help is much appreciated.

答:
Sounds like you need a clearfix.

http://css-tricks.com/snippets/css/clear-fix/

You'll want to define the clearfix class (as stated in the above link) add .clearfix to the #wrapper.

ContentLicense: CC BY-SA 3.0

Title: CSS Height:100% issue


问:
How to embed in memory MariaDB4j to replace default Spring DataSource in JUnit Tests?
I am writing tests for Service that uses several data Jpa repositories. The problem is that some repositories use a lot of native queries with MySQL specific functions such as str_to_date(). So when I tried to test the service's method using H2 I got an error saying that H2 doesn't recognize function. I have tried using H2 in MySQL mode, but got the same error.

here mariaDB4j was proposed as a work-around. I have added dependency into Maven

```<code><dependency>
    <groupId>ch.vorburger.mariaDB4j</groupId>
    <artifactId>mariaDB4j</artifactId>
    <version>2.3.0</version>
    <scope>test</scope>
</dependency>
</code>```

But getting IllegalStateException : Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.

My Test file looks this way:

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
public class TestPay {

    @TestConfiguration
    static class PaymentServiceTestContextConfiguration {
        @Bean
        public PaymentService paymentService(){
            return new PaymentService();
        }
    }

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private TarifRepository firstRepository;
    @Autowired
    private BuildingRepository secondRepository;
    @Autowired
    private ApartmentRepository thirdRepository;

    /* Test cases here*/
}
</code>```

The project is build with Annotation driven Spring Boot.

答:
I build the following class that I reuse in every integration test that requires database access to mariadb. It could probably be improved (and I'd be happy for suggestions), but it works so far:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application-junit.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) //otherwise mariadb is not cleaned up between tests
public abstract class MyIntegrationTest {

    private static MariaDB4jSpringService DB;

    @BeforeClass
    public static void init() throws ManagedProcessException {
        DB = new MariaDB4jSpringService();
        DB.setDefaultPort(1234);
        DB.start();
        DB.getDB().createDB("yourtables");
        DB.getDB().source("schema.sql"); // init scripts from /src/test/resources/schema.sql
    }

    @AfterClass
    public static void cleanup() {
        if (DB != null) DB.stop();
    }
}
</code>```

application-junit.properties:

```<code>spring.datasource.url=jdbc:mariadb://localhost:1234/yourtables
spring.datasource.username=root
spring.datasource.password=
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing tests for Service that uses several data Jpa repositories. The problem is that some repositories use a lot of native queries with MySQL specific functions such as str_to_date(). So when I tried to test the service's method using H2 I got an error saying that H2 doesn't recognize function. I have tried using H2 in MySQL mode, but got the same error.

here mariaDB4j was proposed as a work-around. I have added dependency into Maven

<dependency>
    <groupId>ch.vorburger.mariaDB4j</groupId>
    <artifactId>mariaDB4j</artifactId>
    <version>2.3.0</version>
    <scope>test</scope>
</dependency>

But getting IllegalStateException : Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.

My Test file looks this way:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
public class TestPay {

    @TestConfiguration
    static class PaymentServiceTestContextConfiguration {
        @Bean
        public PaymentService paymentService(){
            return new PaymentService();
        }
    }

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private TarifRepository firstRepository;
    @Autowired
    private BuildingRepository secondRepository;
    @Autowired
    private ApartmentRepository thirdRepository;

    /* Test cases here*/
}

The project is build with Annotation driven Spring Boot.

Body:
I build the following class that I reuse in every integration test that requires database access to mariadb. It could probably be improved (and I'd be happy for suggestions), but it works so far:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application-junit.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) //otherwise mariadb is not cleaned up between tests
public abstract class MyIntegrationTest {

    private static MariaDB4jSpringService DB;

    @BeforeClass
    public static void init() throws ManagedProcessException {
        DB = new MariaDB4jSpringService();
        DB.setDefaultPort(1234);
        DB.start();
        DB.getDB().createDB("yourtables");
        DB.getDB().source("schema.sql"); // init scripts from /src/test/resources/schema.sql
    }

    @AfterClass
    public static void cleanup() {
        if (DB != null) DB.stop();
    }
}

application-junit.properties:

spring.datasource.url=jdbc:mariadb://localhost:1234/yourtables
spring.datasource.username=root
spring.datasource.password=


问:
How can I generate a random number in a certain range?
How can I create an app that generates a random number in Android using Eclipse and then show the result in a TextView field? The random number has to be in a range selected by the user. So, the user will input the max and min of the range, and then I will output the answer.

答:
Below code will help you to generate random numbers between two numbers in the given range:</p>

```<code>private void generateRandomNumbers(int min, int max) {
    // min & max will be changed as per your requirement. In my case, I've taken min = 2 & max = 32

    int randomNumberCount = 10;

    int dif = max - min;
    if (dif < (randomNumberCount * 3)) {
        dif = (randomNumberCount * 3);
    }

    int margin = (int) Math.ceil((float) dif / randomNumberCount);
    List<Integer> randomNumberList = new ArrayList<>();

    Random random = new Random();

    for (int i = 0; i < randomNumberCount; i++) {
        int range = (margin * i) + min; // 2, 5, 8

        int randomNum = random.nextInt(margin);
        if (randomNum == 0) {
            randomNum = 1;
        }

        int number = (randomNum + range);
        randomNumberList.add(number);
    }
    Collections.sort(randomNumberList);
    Log.i("generateRandomNumbers", "RandomNumberList: " + randomNumberList);
}
</code>```

Body:
Below code will help you to generate random numbers between two numbers in the given range:

private void generateRandomNumbers(int min, int max) {
    // min & max will be changed as per your requirement. In my case, I've taken min = 2 & max = 32

    int randomNumberCount = 10;

    int dif = max - min;
    if (dif < (randomNumberCount * 3)) {
        dif = (randomNumberCount * 3);
    }

    int margin = (int) Math.ceil((float) dif / randomNumberCount);
    List<Integer> randomNumberList = new ArrayList<>();

    Random random = new Random();

    for (int i = 0; i < randomNumberCount; i++) {
        int range = (margin * i) + min; // 2, 5, 8

        int randomNum = random.nextInt(margin);
        if (randomNum == 0) {
            randomNum = 1;
        }

        int number = (randomNum + range);
        randomNumberList.add(number);
    }
    Collections.sort(randomNumberList);
    Log.i("generateRandomNumbers", "RandomNumberList: " + randomNumberList);
}


问:
Python code for beams with hdfs support in Pipeline
I am running the Sentiment example here for tensorflow transform.
https://github.com/tensorflow/transform/blob/master/examples/sentiment_example.py

For fn ReadAndShuffleData() defined in line 78-98, is it possible that in a similar way I can load files but from HDFS, not GCS?

I have tried a whole day with several beam API (beams-2.8.0) but failed, and the most promising one I think is using beams.io.hadoopfilesystem. But this fn actually produces a python file-object and cannot be read in using beams.io.ReadFromText() in a beam pipeline.

I also passed in HadoopFileSystemPipelineOptions correctly. Anyone can show me a direction to solve the issue or a 2/3-line code snippets or a workaround? Thank you very much!

p.s. hadoop 2.7.7, beams 2.8 and data is loaded correctly.

I think I may lack some theoretical understandings here, any references will be appreciated!

答:
You might use the apache_beam.Create transform:

Init signature: beam.Create(self, values, reshuffle=True)

Docstring:      A transform that creates a PCollection from an iterable.

import apache_beam as beam
from apache_beam.options.pipeline_options import HadoopFileSystemOptions
from apache_beam.io.hadoopfilesystem import HadoopFileSystem

HDFS_HOSTNAME = 'foo.hadoop.com'
HDFS_PORT = 50070
hdfs_client_options = HadoopFileSystemOptions(hdfs_host=HDFS_HOSTNAME, hdfs_port=HDFS_PORT, hdfs_user="foobar")
hdfs_client = HadoopFileSystem(hdfs_client_options)

input_file_hdfs = "hdfs://foo/bar.csv"
f = hdfs_client.open(input_file_hdfs)

p = beam.Pipeline(options=PipelineOptions())
lines = p | 'ReadMyFile' >> beam.Create(f)
res = lines | "WriteMyFile" >> beam.io.WriteToText("./bar", ".csv")
p.run()
```


问:
customizing bootstrap form-control on select option
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

```<code><div class="form-group row">
    <label for="industry" class="">Industry :</label>
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>
</div>
</code>```

答:
Look up the custom-select class for bootstrap, as it makes it easier for you to style the select element as you need to.

A caveat is however, that support for styling the select/options is fairly limited. If you want full control, you would need to use a third-party package to covert the select to a custom html/javascript based select.

Body:
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

    Industry :
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>


问:
How to access the
 items using Selenium webdriver
I want to access
 items in a webpage.

From the given HTML, how can I access the list items such as User, Make & Model??

I am not able to retrieve the content of the list. My code is not executing the codes added inside the for loop.

HTML:

```<code><li class="nav-item"> <span class="nav-link add-items" data-toggle="collapse" data-target="#add"> <i class="fas fa-plus"></i>   Add</span>
  <ul class="add-menu collapse" id="add">
    <li><span data-toggle="modal" data-target="#add-user-modal">User</span></li>
    <li><span data-toggle="modal" data-target="#add-make-modal">Make</span></li>
    <li><span data-toggle="modal" data-target="#add-model-modal">Model</span></li>
  </ul>
</li>
</code>```

答:
To match a single item you can use the following XPath locator :

```<code>//li/span[text()='User']
</code>```

To match all items and get their text the relevant XPath Expression would be:

```<code>//ul[@class='add-menu collapse']/li/span
</code>```

Example Python code:

```<code>for li in driver.find_elements_by_xpath("//ul[@class='add-menu collapse']/li/span"):
    print(li.text)
</code>```

Title: How to access the <li> items using Selenium webdriver

Body:
I want to access
 items in a webpage.

From the given HTML, how can I access the list items such as User, Make & Model??

I am not able to retrieve the content of the list. My code is not executing the codes added inside the for loop.

HTML:

     Add

User

Make

Model

Body:
To match a single item you can use the following XPath locator :

//li/span[text()='User']

To match all items and get their text the relevant XPath Expression would be:

//ul[@class='add-menu collapse']/li/span

Example Python code:

for li in driver.find_elements_by_xpath("//ul[@class='add-menu collapse']/li/span"):
    print(li.text)


问:
HTML5 Email Validation TLD without Pattern?
How do I tell my input to validate email inputs with the tld?

I don't want to accept email addresses in the form a@b.

I am aware I can specify a regex pattern to assert this behaviour, but this feels like a hacky approach. Is there a native attribute I can use to force the input element to validate the email address, including tld?

<form>
    <input type="email" required="required" pattern="^[^@\s]+@([^@\s]+\.)+[^@\s]+$" value="a@b" />
    <input type="submit"/>
</form>```

答: There isn't a native attribute to validate the TLD. You can use the pattern attribute to validate the TLD though. I have the copy and paste code snippet here: https://github.com/coliff/html5-email-regex</p>


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
If type(distance) is a list then you can simply calculate the average for last 3 points by</p>

```<code>distance = distance[-3:] # This will remove the extra data and get only last 3 values

average = sum(distance) / len(distance)
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
If type(distance) is a list then you can simply calculate the average for last 3 points by

distance = distance[-3:] # This will remove the extra data and get only last 3 values

average = sum(distance) / len(distance)


问:
Combinations in the right order
I am dealing with combinations of variables. In my model the combination (A,B) would be similar to (B,A). I would like to reshape my data in order to get similar combinations in the same order.

I try to used the duplicated function and to work with the paste function but I do not sort out the issue.

This is my first table :

```<code>df <- data.frame(V1=c("A","A","A","B","B","B"),
                 V2=c("B","C","D","A","D","A"))
</code>```

This what I would like to obtain :

```<code>df2 <- data.frame(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Test=c("OK","OK","OK","FALSE","OK","FALSE"),
                  V1b=c("A","A","A","A","B","A"),
                  V2b=c("B","C","D","B","D","B"))
</code>```

答:
With dplyr, you can do:

```<code>df %>%
 mutate(V1b = pmin(V1, V2),
        V2b = pmax(V1, V2),
        Test = paste0(V1, V2) != paste0(V1b, V2b))

  V1 V2 V1b V2b  Test
1  A  B   A   B FALSE
2  A  C   A   C FALSE
3  A  D   A   D FALSE
4  B  A   A   B  TRUE
5  B  D   B   D FALSE
6  B  A   A   B  TRUE
</code>```

Title: Combinations in the right order

Body:
I am dealing with combinations of variables. In my model the combination (A,B) would be similar to (B,A). I would like to reshape my data in order to get similar combinations in the same order.

I try to used the duplicated function and to work with the paste function but I do not sort out the issue.

This is my first table :

df <- data.frame(V1=c("A","A","A","B","B","B"),
                 V2=c("B","C","D","A","D","A"))

This what I would like to obtain :

df2 <- data.frame(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Test=c("OK","OK","OK","FALSE","OK","FALSE"),
                  V1b=c("A","A","A","A","B","A"),
                  V2b=c("B","C","D","B","D","B"))

Body:
With dplyr, you can do:

df %>%
 mutate(V1b = pmin(V1, V2),
        V2b = pmax(V1, V2),
        Test = paste0(V1, V2) != paste0(V1b, V2b))

  V1 V2 V1b V2b  Test
1  A  B   A   B FALSE
2  A  C   A   C FALSE
3  A  D   A   D FALSE
4  B  A   A   B  TRUE
5  B  D   B   D FALSE
6  B  A   A   B  TRUE


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答: Outsource. Go to rentacoder.com or similar.</p>

OwnerDisplayName: Cip

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Dave


问:
Max function with tuple key [Updated]
I'm trying to understand what happened in the following line:

```<code>print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))
</code>```

My understanding is, the lambda will return a tuple for each element in the list [1, -2, 3, -1].

But how can a list be compared with a tuple?

And why the output is 1, instead of 3 ?

I've tried

```<code>print(max([1, -2, 3, -1], key=(-1, 1), default=0))
</code>```

But it said uple is not callable

The key to understand the problem here is the key function used. If it's hard to understand, i recommend you to read this and play with sort rather max (cause sort will give you a informational anwser)

My understanding:

Step 1. the lambda function convert a = [1, -2, 3, -1] to a new one b = [(-1, 1), (-2, -2), (-3, 3), (-1, 1)]

Step 2. max/sort will deal with the new listb. It will first compare the first element, if it's tied, compare the second

Step3. convert the sorted(b) in terms of a

答:
The max function goes through each element of your list and applies the lambda function to determine the value of each item, giving you:

```<code>[(-1,1), (-2,-2), (-3,3), (-1,-1)]
</code>```

It then runs max, which by default first compares the item at the first index of each tuple. Since the first element is negative in all cases, -1 is the largest first element, which corresponds to the 1 and -1 in the original array. Since there's a tie, it then compares the second element giving (-1,1) as the largest element in this new array, which corresponds to 1 in the original.

Title: Max function with tuple key [Updated]

Body:
I'm trying to understand what happened in the following line:

print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))

My understanding is, the lambda will return a tuple for each element in the list [1, -2, 3, -1].

But how can a list be compared with a tuple?

And why the output is 1, instead of 3 ?

I've tried

print(max([1, -2, 3, -1], key=(-1, 1), default=0))

But it said uple is not callable

The key to understand the problem here is the key function used. If it's hard to understand, i recommend you to read this and play with sort rather max (cause sort will give you a informational anwser)

My understanding:

Step 1. the lambda function convert a = [1, -2, 3, -1] to a new one b = [(-1, 1), (-2, -2), (-3, 3), (-1, 1)]

Step 2. max/sort will deal with the new listb. It will first compare the first element, if it's tied, compare the second

Step3. convert the sorted(b) in terms of a

Body:
The max function goes through each element of your list and applies the lambda function to determine the value of each item, giving you:

[(-1,1), (-2,-2), (-3,3), (-1,-1)]

It then runs max, which by default first compares the item at the first index of each tuple. Since the first element is negative in all cases, -1 is the largest first element, which corresponds to the 1 and -1 in the original array. Since there's a tie, it then compares the second element giving (-1,1) as the largest element in this new array, which corresponds to 1 in the original.


问:
hsts deprecated The "includeSubdomain" paramter is deprecated
I have a loopback 3 application. When I start the application with . node I get this in my console.

```<code>hsts deprecated The "includeSubdomain" parameter is deprecated. Use "includeSubDomains" (with a capital D) instead. node_modules/loopback/lib/server-app.js:74:25
</code>```

I searched in my node_modules folder, but there isn't a loopback folder. So how can I fix this?

答:
I am having same error too,
But just viewing on PM2 logs to see that.

Do you use Loopback with PM2 or inside a Docker container?

I dont have this error with running "NODE . "

Body:
I have a loopback 3 application. When I start the application with . node I get this in my console.

hsts deprecated The "includeSubdomain" parameter is deprecated. Use "includeSubDomains" (with a capital D) instead. node_modules/loopback/lib/server-app.js:74:25

I searched in my node_modules folder, but there isn't a loopback folder. So how can I fix this?


问:
How to use search view defined in menuoptions of the MainActivity in fragments?
I am trying to use the searchview in the toolbar (menu) in multiple fragments. So, if I switch to various fragments, the searchview would apply to and search only that fragment then. After defining it in the MainActivity, how do I use it in the fragments?</p>

答:
You should keep reference to your fragments like you want. Then depending from your situation, when you typing the request or any other way, you need to make search in your fragment, like this:

```<code>myFragment.doSearch(query)
</code>```

If you have a list of frargments and you need to make a call only in currently visible, you can define the isActuallyVisible variable in each fragment(on in BaseFragment if you have one) and change it like this:

```<code>public void setMenuVisibility(final boolean visible) {
    super.setMenuVisibility(visible);
    isActuallyVisible = visible;
}
</code>```

Then you can make search like this:

```<code>for (Fragment frag : fragmentsList) {
    if (frag.isActuallyVisible) {
        frag.doSearch(query);
        break;
    }
}
</code>```

Hope this will help you to find the correct solution

Body:
You should keep reference to your fragments like you want. Then depending from your situation, when you typing the request or any other way, you need to make search in your fragment, like this:

myFragment.doSearch(query)

If you have a list of frargments and you need to make a call only in currently visible, you can define the isActuallyVisible variable in each fragment(on in BaseFragment if you have one) and change it like this:

public void setMenuVisibility(final boolean visible) {
    super.setMenuVisibility(visible);
    isActuallyVisible = visible;
}

Then you can make search like this:

for (Fragment frag : fragmentsList) {
    if (frag.isActuallyVisible) {
        frag.doSearch(query);
        break;
    }
}

Hope this will help you to find the correct solution


问:
Error: data and salt arguments required
I am trying to save a user to mongodb database using post request as follow, but I got the error bcrypt Error: data and hash arguments required .It's a pretty simple set up of the code but i can't figure out anything wrong with it.
models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
 name: {
  type: String,
 },
 email: {
  type: String,
  required: true
 },
 username:{
  type: String,
  required: true
 },
 password: {
  type: String,
  required: true
 }
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id,callback){
 User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
 const query = {username:username}
 User.findOne(query,callback);
}

module.exports.addUser= function (newUser, callback) {
   bcrypt.genSalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
        if(err) throw (err);

        newUser.password=hash;
        newUser.save(callback);
    });
   });
}```
</div>
</div>

routes/users.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const jwt = require('jsonwebtoken');
User = require('../models/users')

// // Register
router.post('/register', (req, res, next) => {
  var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      // res.json({success: false, msg:'Failed to register user'});
    } else {
      // res.json({success: true, msg:'User registered'});
    }

  });

});

// Authenticate
router.post('/authenticate', (req, res, next) => {
  res.send('AUTHENTICATE');
});

// Profile
router.get('/profile', (req, res, next) => {
  res.send('PROFILE');
});

module.exports = router;</code>```

Server was running but after using postman chrome post request error are shown and server stop working as errors shown in image.

答: Remove the arrow => in bcrypt.hash() . Use old fashioned method definition function() {}

Title: Error: data and salt arguments required

Body:
I am trying to save a user to mongodb database using post request as follow, but I got the error bcrypt Error: data and hash arguments required .It's a pretty simple set up of the code but i can't figure out anything wrong with it.
models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
 name: {
  type: String,
 },
 email: {
  type: String,
  required: true
 },
 username:{
  type: String,
  required: true
 },
 password: {
  type: String,
  required: true
 }
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id,callback){
 User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
 const query = {username:username}
 User.findOne(query,callback);
}

module.exports.addUser= function (newUser, callback) {
   bcrypt.genSalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
        if(err) throw (err);

        newUser.password=hash;
        newUser.save(callback);
    });
   });
}

routes/users.js

const jwt = require('jsonwebtoken');
User = require('../models/users')

// // Register
router.post('/register', (req, res, next) => {
  var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      // res.json({success: false, msg:'Failed to register user'});
    } else {
      // res.json({success: true, msg:'User registered'});
    }

  });

});

// Authenticate
router.post('/authenticate', (req, res, next) => {
  res.send('AUTHENTICATE');
});

// Profile
router.get('/profile', (req, res, next) => {
  res.send('PROFILE');
});

module.exports = router;

Server was running but after using postman chrome post request error are shown and server stop working as errors shown in image.


问:
major() and minor() function in linux kernel
Hi I'm running vfs_stat, fd is an opened file desciptor of /dev/tty0:

```<code>set_fs (KERNEL_DS);
if (vfs_fstat (fd, &stat))
{
    goto out3;
}

if (stat.mode & S_IFCHR)
    printk (KERN_INFO "opening %s (dev %d)\n", filename, stat.rdev);
</code>```

And it prints:

```<code>[ 8657.480625] opening /dev/tty0 (dev 4194304)
</code>```

So now I need to retrieve major number of the device, but I couldn't find major() or minor() definition in linux kernel.

I found this answer but it doesn't seem to be right:

```<code>#define major(dev) ((int)(((unsigned int) (dev) >> 8) & 0xff))
#define minor(dev) ((int)((dev) & 0xff))
</code>```

Because if I do printk (KERN_INFO "opening %s (dev %d)\n", filename, major (stat.rdev)); The second field is always zero.

How should I get the major number then?

答:
On recent glibc and kernels, you should include sys/sysmacros.h and not only   sys/types.h. Here is the comment that describe this decision:</p>

```<code>/* BSD defines `major', `minor', and `makedev' in this header.
   However, these symbols are likely to collide with user code, so we are
   going to stop defining them here in an upcoming release.  Code that needs
   these macros should include <sys/sysmacros.h> directly.  Code that does
   not need these macros should #undef them after including this header.  */
# define __SYSMACROS_DEPRECATED_INCLUSION
# include <sys/sysmacros.h>
# undef __SYSMACROS_DEPRECATED_INCLUSION
</code>```

Body:
Hi I'm running vfs_stat, fd is an opened file desciptor of /dev/tty0:

set_fs (KERNEL_DS);
if (vfs_fstat (fd, &stat))
{
    goto out3;
}

if (stat.mode & S_IFCHR)
    printk (KERN_INFO "opening %s (dev %d)\n", filename, stat.rdev);

And it prints:

[ 8657.480625] opening /dev/tty0 (dev 4194304)

So now I need to retrieve major number of the device, but I couldn't find major() or minor() definition in linux kernel.

I found this answer but it doesn't seem to be right:

#define major(dev) ((int)(((unsigned int) (dev) >> 8) & 0xff))
#define minor(dev) ((int)((dev) & 0xff))

Because if I do printk (KERN_INFO "opening %s (dev %d)\n", filename, major (stat.rdev)); The second field is always zero.

How should I get the major number then?

Body:
On recent glibc and kernels, you should include sys/sysmacros.h and not only   sys/types.h. Here is the comment that describe this decision:

/* BSD defines `major', `minor', and `makedev' in this header.
   However, these symbols are likely to collide with user code, so we are
   going to stop defining them here in an upcoming release.  Code that needs
   these macros should include <sys/sysmacros.h> directly.  Code that does
   not need these macros should #undef them after including this header.  */
# define __SYSMACROS_DEPRECATED_INCLUSION
# include <sys/sysmacros.h>
# undef __SYSMACROS_DEPRECATED_INCLUSION


问:
Convert PHP variable to JQuery
Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery

View:

```<code><?php
    foreach ($muziek as $ms)
    {
        if ($ms->id == 2) {
            echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
            echo '</audio>';
        }
    }

    foreach ($muziek as $ms)
    {
        echo '<br>';
        echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
    }
?>
</div>

<script>
    $("input").click(function () {
       var test = $(this).attr("id");
       console.log(test);
       //Here needs to be the foreach muziek
    });
</script>
</code>```

Muziek variable:
This is how i fill the music variable

```<code>function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    return $muziek;
}
</code>```

Does someone has an idea or show me how this can be done?

答:
Convert $muziek into javascript array using json_encode

```<code><script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>
</code>```

Title: Convert PHP variable to JQuery

Body:
Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery

View:

<?php
    foreach ($muziek as $ms)
    {
        if ($ms->id == 2) {
            echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
            echo '</audio>';
        }
    }

    foreach ($muziek as $ms)
    {
        echo '
';
        echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
    }
?>

Muziek variable:
This is how i fill the music variable

function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    return $muziek;
}

Does someone has an idea or show me how this can be done?

Body:
Convert $muziek into javascript array using json_encode

<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>


问:
Disable HTML5 <video> playsinline for iPad
I would like to explore if it is possible to disable playsinline for HTML5 <video> on iOS, specifically for iPad. My video tag (below) does NOT include playsinline, as I wish the video to open in the native iOS video player.

Since iOS10, Apple have enabled the ability to use playsinline, however for this project I do not want this. During testing however, it seems that regardless of wether or not the attribute exists, on iPad the video will play inline regardless and I would like to disable this, forcing the native iOS player instead (just like on iPhone).

I found the following article, which states: 'When adding a video element to a HTML document on the iPhone, you must also include the playsinline attribute. The default value for iPhone is false and the default value for iPad is true."

The above suggests that this is the reason for my problem, but I'm unsure how to resolve?

Many thanks.

```<code><video src="myurl.com" preload loop></video>
</code>```

答:
If you are happy to have the same behaviour on all devices, you can explicitly assign a value to the attribute in your HTML5 code:

<video src="myurl.com" preload loop playsinline="false"></video>
```

Body:
I would like to explore if it is possible to disable playsinline for HTML5 <video> on iOS, specifically for iPad. My video tag (below) does NOT include playsinline, as I wish the video to open in the native iOS video player.

Since iOS10, Apple have enabled the ability to use playsinline, however for this project I do not want this. During testing however, it seems that regardless of wether or not the attribute exists, on iPad the video will play inline regardless and I would like to disable this, forcing the native iOS player instead (just like on iPhone).

I found the following article, which states: 'When adding a video element to a HTML document on the iPhone, you must also include the playsinline attribute. The default value for iPhone is false and the default value for iPad is true."

The above suggests that this is the reason for my problem, but I'm unsure how to resolve?

Many thanks.

<video src="myurl.com" preload loop></video>


问:
Does `fprintf()` and `fscanf()` in Windows require a file to be opened in text mode
When using fprintf() and fscanf() on text files in Windows, is it necessary or recommended to open the file in text mode compared to binary mode?

Does the answer depend on using Microsoft's implementation of the standard C library or GNU Libc in Windows?

答:
In windows, binary or text mode differ by end of line conversion.

The system does the end-of-line conversion (through low-level POSIX write and read for instance). But it doesn't matter: end of line conversion is performed in text mode, and nothing is changed in binary mode.

The printf and other formatting functions end up calling a low-level read/write/whatever function that handles this end-of-line conversion.

When you write a newline character \n in a file opened in text mode, the system adds an \r character before the newline.

When you read \n in a file opened in text mode, the system removes the \r character which is before the newline. If there isn't, it doesn't remove anything. If there are 2 \r characters, it only removes one.

Note that writing text files in binary mode can be useful if you want to write Linux-compliant text files, without \r character.


问:
Log::info - Logging user logout in laravel.log
I want add all activities inside my app in the larave.log file.
I was able to add user login inside it but not the logout.

I do that using Laravel 5.8 with a mysql 5 database.

This is code inside HomeController for registering login user loading home view.

```<code>public function index()
{
    Log::info('Utente collegato: '.Auth::user()->name);
    return view( config('configpath.user_home') );// loading user homepage
}
</code>```

The code below is inside Laravel default LoginController

```<code>public function userLogout()
{
    Log::info('User '.Auth::user()->name. 'has logged out');
    Auth::guard('web')->logout();
    return redirect()->route('login');
}
</code>```

With logout I expect to see the message about user logout as in login but I don't see it. Someone can give me an explanation? Thanks!

答:
You can listen for the Login and Logout event to log the actions. To to so, add the following to the boot() method of your EventServiceProvider:

```<code>Event::listen(\Illuminate\Auth\Events\Login::class, function ($event) {
    \Log::info("User login: {$event->user->name}");
});

Event::listen(\Illuminate\Auth\Events\Logout::class, function ($event) {
    \Log::info("User logout: {$event->user->name}");
});
</code>```

Using this method, you don't have to override the existing and framework-provided controller actions.

Body:
I want add all activities inside my app in the larave.log file.
I was able to add user login inside it but not the logout.

I do that using Laravel 5.8 with a mysql 5 database.

This is code inside HomeController for registering login user loading home view.

public function index()
{
    Log::info('Utente collegato: '.Auth::user()->name);
    return view( config('configpath.user_home') );// loading user homepage
}

The code below is inside Laravel default LoginController

public function userLogout()
{
    Log::info('User '.Auth::user()->name. 'has logged out');
    Auth::guard('web')->logout();
    return redirect()->route('login');
}

With logout I expect to see the message about user logout as in login but I don't see it. Someone can give me an explanation? Thanks!

Body:
You can listen for the Login and Logout event to log the actions. To to so, add the following to the boot() method of your EventServiceProvider:

Event::listen(\Illuminate\Auth\Events\Login::class, function ($event) {
    \Log::info("User login: {$event->user->name}");
});

Event::listen(\Illuminate\Auth\Events\Logout::class, function ($event) {
    \Log::info("User logout: {$event->user->name}");
});

Using this method, you don't have to override the existing and framework-provided controller actions.


问:
How to use the Device's Default Font in Flutter?
I opened a Java native Android app and a Flutter Android app on the same device and took screenshots of both of the applications:

As you can see, the fonts are they are using to display their text are different.

Both applications were run using the Samsung Galaxy S5 Choco Cooky default theme.

The Java native app adapts and displays the custom Samsung Galaxy font, whereas the Flutter app does not adjust fonts.

How can I configure my Flutter app to use the device's default font?

答:
In Flutter, default font on Android is Roboto, and on iOS is .SF UI Pro and .SF UI Text.

check out this answer https://stackoverflow.com/a/56339147/1776125

on iOS this is OK, but on android there are lots of ROMs with different default font family.

In order to get the device default font family, I wrote a platform channel on Android, here is the code to get device default font family:

```<code>private String getDefaultFont() {
        File configFilename = new File("/system/etc/system_fonts.xml");
        // sans-serif is the default font family name in Android SDK, check out the code in Typeface.java
        String defaultFontName = "sans-serif";

        try {
            FileInputStream fontsIn = new FileInputStream(configFilename);
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(fontsIn, null);
            boolean done = false;
            boolean getTheText = false;
            int eventType;
            while (!done) {
                eventType = parser.next();
                if (eventType == parser.START_TAG && parser.getName().equalsIgnoreCase("name")) {
                    getTheText = true;
                }
                if (eventType == parser.TEXT && getTheText) {
                    // first name
                    defaultFontName = parser.getText();
                    done = true;
                }
                if (eventType == parser.END_DOCUMENT) {
                    done = true;
                }
            }
        } catch (RuntimeException e) {
            System.err.println("Didn't create default family (most likely, non-Minikin build)");
        } catch (FileNotFoundException e) {
            System.err.println("GetDefaultFont: config file Not found");
        } catch (IOException e) {
            System.err.println("GetDefaultFont: IO exception: " + e.getMessage());
        } catch (XmlPullParserException e) {
            System.err.println("getDefaultFont: XML parse exception " + e.getMessage());
        }
        return defaultFontName;
    }
</code>```

Body:
In Flutter, default font on Android is Roboto, and on iOS is .SF UI Pro and .SF UI Text.

check out this answer https://stackoverflow.com/a/56339147/1776125

on iOS this is OK, but on android there are lots of ROMs with different default font family.

In order to get the device default font family, I wrote a platform channel on Android, here is the code to get device default font family:

private String getDefaultFont() {
        File configFilename = new File("/system/etc/system_fonts.xml");
        // sans-serif is the default font family name in Android SDK, check out the code in Typeface.java
        String defaultFontName = "sans-serif";

        try {
            FileInputStream fontsIn = new FileInputStream(configFilename);
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(fontsIn, null);
            boolean done = false;
            boolean getTheText = false;
            int eventType;
            while (!done) {
                eventType = parser.next();
                if (eventType == parser.START_TAG && parser.getName().equalsIgnoreCase("name")) {
                    getTheText = true;
                }
                if (eventType == parser.TEXT && getTheText) {
                    // first name
                    defaultFontName = parser.getText();
                    done = true;
                }
                if (eventType == parser.END_DOCUMENT) {
                    done = true;
                }
            }
        } catch (RuntimeException e) {
            System.err.println("Didn't create default family (most likely, non-Minikin build)");
        } catch (FileNotFoundException e) {
            System.err.println("GetDefaultFont: config file Not found");
        } catch (IOException e) {
            System.err.println("GetDefaultFont: IO exception: " + e.getMessage());
        } catch (XmlPullParserException e) {
            System.err.println("getDefaultFont: XML parse exception " + e.getMessage());
        }
        return defaultFontName;
    }


问:
AWS Certificate - Unrecognized keystore format: null
I'm trying to generate AWS IoT cerificate from certificate and private key. First I'm creating PKCS12 keystore, then convert PKCS12 keystore to a BKS (BouncyCastle) keystore. While doing second step, I'm getting error:

```<code>keytool error: java.security.KeyStoreException: Unrecognized keystore format: null
</code>```

What's weird: I'm doing it second time, few months ago I did it the same way, and then it worked, so I'm sure my files are correct. Command I'm using is (new lines only for readability here):

```<code>"C:\Program Files\Java\jdk-10.0.2\bin\keytool"
-importkeystore
-srckeystore beurer_keystore.p12
-srcstoretype pkcs12
-srcstorepass password
-destkeystore beurer_keystore.bks
-deststoretype bks
-deststorepass password
--provider org.bouncycastle.jce.provider.BouncyCastleProvider
--providerpath bcprov-jdk15on-160.jar
</code>```

What could changed that this time I'm getting different result? Different Java version? Different keytool?

答:
It appears to be a bug 1, 2.  I too get the error with macOS / Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode):

```<code>keytool error: java.security.KeyStoreException: Unrecognized keystore format: null
java.security.KeyStoreException: Unrecognized keystore format: null
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1815)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1687)
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:1308)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:397)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:390)
</code>```

I don't get an error using OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.10.1) on Ubuntu 18.10.

I can reproduce the spurious error by simply listing BouncyCastle keystores:

```<code>keytool -list -v -storepass "donottell" -keystore "ssl/keystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk15on-1.61.jar" -storetype BKS
</code>```

Body:
I'm trying to generate AWS IoT cerificate from certificate and private key. First I'm creating PKCS12 keystore, then convert PKCS12 keystore to a BKS (BouncyCastle) keystore. While doing second step, I'm getting error:

keytool error: java.security.KeyStoreException: Unrecognized keystore format: null

What's weird: I'm doing it second time, few months ago I did it the same way, and then it worked, so I'm sure my files are correct. Command I'm using is (new lines only for readability here):

"C:\Program Files\Java\jdk-10.0.2\bin\keytool"
-importkeystore
-srckeystore beurer_keystore.p12
-srcstoretype pkcs12
-srcstorepass password
-destkeystore beurer_keystore.bks
-deststoretype bks
-deststorepass password
--provider org.bouncycastle.jce.provider.BouncyCastleProvider
--providerpath bcprov-jdk15on-160.jar

What could changed that this time I'm getting different result? Different Java version? Different keytool?

Body:
It appears to be a bug 1, 2.  I too get the error with macOS / Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode):

keytool error: java.security.KeyStoreException: Unrecognized keystore format: null
java.security.KeyStoreException: Unrecognized keystore format: null
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1815)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1687)
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:1308)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:397)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:390)

I don't get an error using OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.10.1) on Ubuntu 18.10.

I can reproduce the spurious error by simply listing BouncyCastle keystores:

keytool -list -v -storepass "donottell" -keystore "ssl/keystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk15on-1.61.jar" -storetype BKS


答:
When using fprintf() and fscanf() on text files in Windows, is it necessary or recommended to open the file in text mode compared to binary mode?

fprintf / fscanf are based on low level function fputc / fgetc etc so the management of the mode text/binary follow the same rules we see in Do fgetc, fputc, fgets and fputs require a file opened in text mode, and fread and fwrite require a file in binary mode?

Does the answer depend on using Microsoft's implementation of the standard C library or GNU Libc in Windows?

The mingw libc are supported my the Microsoft libs, the behavior is the one of the Microsoft libc, some function follow ISO but not GNU / gcc which is an implementation, not a standard. Note generally Microsoft is not fully conformant to any specific POSIX standard (see Compatibility in Microsoft Docs )

Title: Does `fprintf()` and `fscanf()` in Windows require a file to be opened in text mode

Body:
When using fprintf() and fscanf() on text files in Windows, is it necessary or recommended to open the file in text mode compared to binary mode?

Does the answer depend on using Microsoft's implementation of the standard C library or GNU Libc in Windows?


问:
MongoDB (pymongo) $avg and $stdDevPop do not work inside $project, but they work perfectly inside $group
I am trying to find the Average ($avg) and the Standard Deviation ($stdDevPop) in a collection, check if the Average value is larger than the Standard Deviation value, and, depending on this, use the larger one as a optimalCredit value .

If I use $avg and $stdDevPop inside $group, they work without issues, but, when I place them inside a $project, they return Null

I am really new to Mongo (yesterday morning I made my first query) so I know I must me understanding something wrong.

This is the code I came up with to compare the Average ($avg) and the Standard Deviation ($stdDevPop):

```<code>{'$match':
      {'charRange':
          {'$gt': 0},
      'countPar':
          {'$gte': 0}
},

{'$group':
      {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
       'count':
          {'$sum': 1}
      }
},

{'$project':
     {'optimalCredit':
          {'$cond':
              {'if':
                    {'$gt': [
                             {'$avg': 'credit'},
                             {'$stdDevPop': 'credit'}
                            ]
                    },
               'then':
                    {'$avg': '$credit'},
               'else':
                    {'$stdDevPop': '$credit'}
              }
          }
     }
},

{'$sort':
     {'optimalCredit': -1}
}
</code>```

This is the code I tested with to see if $avg and th $stdDevPop work and return data:

```<code>{'$match':
     {'charRange':
          {'$gt': 0},
     'countPar':
          {'$gte': 0},
     }
},

{'$group':
    {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
           'creditAvg':
                 {'$avg': '$credit'},
           'creditStdDev':
                 {'$stdDevPop':'$credit'},
           'count': {'$sum': 1}
    }
}
</code>```

This is what I am getting back when using $project:

```<code>{'_id': {'parNr': 7, 'charRange': 1500}, 'optimalCredit': None}
</code>```

This is what I am getting if I remove $project and move $avg and $stdDevPop in $group:

```<code>{'_id': {'charRange': 1500, 'parNr': 7}, 'creditStdDev': 19.430788855719562, 'count': 9, 'creditAvg': 16.0}
</code>```

Finally, this is the way it should look (using the numbers above):

```<code>{'_id': {'parNr': 7, 'charRange': 1500}, 'count': 9, 'optimalCredit': 19.430788855719562}
</code>```

答:
I got it. I needed to declare the average ($avg) and standard deviation ($stdDevPop) in the $group and then call these 2 from the $project

```<code>{'$match':
      {'charRange':
          {'$gt': 0},
      'countPar':
          {'$gte': 0}
},

{'$group':
      {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
       'count': {'$sum': 1},
       'creditAvg': {'$avg': '$credit'},
       'creditStdDev': {'$stdDevPop': '$credit'}
      }
},

{'$project':
     {'count': '$count',
      'creditAvg': '$creditAvg',
      'creditStdDev': '$creditStdDev',
      'optimalCredit':
          {'$cond':
              {'if':
                    {'$gt': [
                             '$creditAvg',
                             '$creditStdDev'
                            ]
                    },
               'then': '$creditAvg',
               'else': '$creditStdDev'
              }
          }
     }
},

{'$sort':
     {'optimalCredit': -1}
}
</code>```

Body:
I am trying to find the Average ($avg) and the Standard Deviation ($stdDevPop) in a collection, check if the Average value is larger than the Standard Deviation value, and, depending on this, use the larger one as a optimalCredit value .

If I use $avg and $stdDevPop inside $group, they work without issues, but, when I place them inside a $project, they return Null

I am really new to Mongo (yesterday morning I made my first query) so I know I must me understanding something wrong.

This is the code I came up with to compare the Average ($avg) and the Standard Deviation ($stdDevPop):

{'$match':
      {'charRange':
          {'$gt': 0},
      'countPar':
          {'$gte': 0}
},

{'$group':
      {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
       'count':
          {'$sum': 1}
      }
},

{'$project':
     {'optimalCredit':
          {'$cond':
              {'if':
                    {'$gt': [
                             {'$avg': 'credit'},
                             {'$stdDevPop': 'credit'}
                            ]
                    },
               'then':
                    {'$avg': '$credit'},
               'else':
                    {'$stdDevPop': '$credit'}
              }
          }
     }
},

{'$sort':
     {'optimalCredit': -1}
}

This is the code I tested with to see if $avg and th $stdDevPop work and return data:

{'$match':
     {'charRange':
          {'$gt': 0},
     'countPar':
          {'$gte': 0},
     }
},

{'$group':
    {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
           'creditAvg':
                 {'$avg': '$credit'},
           'creditStdDev':
                 {'$stdDevPop':'$credit'},
           'count': {'$sum': 1}
    }
}

This is what I am getting back when using $project:

{'_id': {'parNr': 7, 'charRange': 1500}, 'optimalCredit': None}

This is what I am getting if I remove $project and move $avg and $stdDevPop in $group:

{'_id': {'charRange': 1500, 'parNr': 7}, 'creditStdDev': 19.430788855719562, 'count': 9, 'creditAvg': 16.0}

Finally, this is the way it should look (using the numbers above):

{'_id': {'parNr': 7, 'charRange': 1500}, 'count': 9, 'optimalCredit': 19.430788855719562}

Body:
I got it. I needed to declare the average ($avg) and standard deviation ($stdDevPop) in the $group and then call these 2 from the $project

{'$match':
      {'charRange':
          {'$gt': 0},
      'countPar':
          {'$gte': 0}
},

{'$group':
      {'_id':
          {'charRange': '$charRange', 'parNr': '$countPar'},
       'count': {'$sum': 1},
       'creditAvg': {'$avg': '$credit'},
       'creditStdDev': {'$stdDevPop': '$credit'}
      }
},

{'$project':
     {'count': '$count',
      'creditAvg': '$creditAvg',
      'creditStdDev': '$creditStdDev',
      'optimalCredit':
          {'$cond':
              {'if':
                    {'$gt': [
                             '$creditAvg',
                             '$creditStdDev'
                            ]
                    },
               'then': '$creditAvg',
               'else': '$creditStdDev'
              }
          }
     }
},

{'$sort':
     {'optimalCredit': -1}
}


问:
Scanning Java annotations at runtime
How do I search the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system finds these classes while loading so they are accessible remotely.

答:
Spring has something called a AnnotatedTypeScanner class.

This class internally uses

```<code>ClassPathScanningCandidateComponentProvider
</code>```

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

```<code>/**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     *
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }
</code>```

OwnerDisplayName: Alotor

Title: Scanning Java annotations at runtime

LastEditorDisplayName: Alotor

Body:
Spring has something called a AnnotatedTypeScanner class.

This class internally uses

ClassPathScanningCandidateComponentProvider

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

/**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     *
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }


问:
"HTTP ERROR 403" while executing script for clicking on search button which works fine with manual click
I am trying to click on Search button after entering data in some fields which has to show the results(list of flight available from city A to city B on t he selected date) according to the search in the same page.

When I run the Selenium - Java script for this scenario system is showing HTTP ERROR 403, while it works fine when I do it manually.

答:
403 Forbidden

The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.

This status is similar to 401, but in this case, re-authenticating will make no difference. The access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource.

Status

```<code>403 Forbidden
</code>```

Example response

```<code>HTTP/1.1 403 Forbidden
Date: Wed, 28 May 2019 07:28:00 GMT
</code>```

Reason

You code trials and the error trace log would have helped us to debug the issue in a better way. Possibly the WebDriver controlled Browser Client is getting detected and hence the subsequent requests are getting blocked.

Outro

You can find similar discussions in:

Failed to load resource: the server responded with a status of 429 (Too Many Requests) and 404 (Not Found) with ChromeDriver Chrome through Selenium

Unable to use Selenium to automate Chase site login

Body:
403 Forbidden

The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.

This status is similar to 401, but in this case, re-authenticating will make no difference. The access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource.

Status

403 Forbidden

Example response

HTTP/1.1 403 Forbidden
Date: Wed, 28 May 2019 07:28:00 GMT

Reason

You code trials and the error trace log would have helped us to debug the issue in a better way. Possibly the WebDriver controlled Browser Client is getting detected and hence the subsequent requests are getting blocked.

Outro

You can find similar discussions in:

Failed to load resource: the server responded with a status of 429 (Too Many Requests) and 404 (Not Found) with ChromeDriver Chrome through Selenium

Unable to use Selenium to automate Chase site login


问:
is there any API's is exists for uploading a file into the share point (office 365)?
Is there any API's there to upload a file to the share point location (office 365) ?

I have already tried with graph Api but which have only get method so please assist me on this,

I have already gone through below links,

https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/upload-a-file-by-using-the-rest-api-and-jquery

答:
There are 2 options

For uploading files smaller than 4MB:
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=cs

For uploading files bigger than 4MB they have to be uploaded in batched using
https://learn.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0


问:
Find elemtnt*s* return array with same element
I've been up on this for 2 days.

Trying to get all Text(s) from span(s), which appear in many div(s).

All the div(s) looks pretty much the same :

```<code><div class="_3_7SH _3DFk6 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">TEXT TO COPY IS ME</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>

</code>```

This is how tried to find ALL "message-in" elements :

in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

I got back the length of the array: 11

Then, tried to get all text from span(s):

```<code>for index in in_mesg_arr:
   last_msg = last_msg + str(index.find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)
</code>```

HOWEVER, i get back the same text (same element over and over!).

print(last_msg) = bla bla bla bla bla bla bla bla bla bla bla

Will be glad to get some directions.

FULL HTML:

答:
These can be done using BeautifulSoup</p>

```<code>from bs4 import BeautifulSoup
content = '''
    <div> class = "*something* message-in *something*" <div>
    <span> class = "selectable-text invisible-space copyable-text" <span>
    '''
soup = BeautifulSoup(content,"lxml")

span_text =  [x.get_text() for x in  soup.find_all('span')]

html_con = '''
<div class="_3_7SH _3DFk6 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">TEXT TO COPY IS ME</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>
<div class="_3_7SH _3DFk6123456 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">New text</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>
'''

soup = BeautifulSoup(html_con)

content_message_in= soup.find_all('div', {'class': 'message-in'})
span_content =[x.find_all('span') for x in content_message_in]
span_text  = [x[0].get_text() for x in span_content]

#o/p
['TEXT TO COPY IS ME', 'New text']
</code>```

Body:
I've been up on this for 2 days.

Trying to get all Text(s) from span(s), which appear in many div(s).

All the div(s) looks pretty much the same :

TEXT TO COPY IS ME

10:26 AM

This is how tried to find ALL "message-in" elements :

in_mesg_arr = driver.find_elements_by_xpath("//div[contains(@class, 'message-in')]")

I got back the length of the array: 11

Then, tried to get all text from span(s):

for index in in_mesg_arr:
   last_msg = last_msg + str(index.find_element_by_xpath(
    "//span[contains(@class,'selectable-text invisible-space copyable-text')]").text)

HOWEVER, i get back the same text (same element over and over!).

print(last_msg) = bla bla bla bla bla bla bla bla bla bla bla

Will be glad to get some directions.

FULL HTML:

Body:
These can be done using BeautifulSoup

from bs4 import BeautifulSoup
content = '''
    <div> class = "*something* message-in *something*" <div>
    <span> class = "selectable-text invisible-space copyable-text" <span>
    '''
soup = BeautifulSoup(content,"lxml")

span_text =  [x.get_text() for x in  soup.find_all('span')]

html_con = '''
<div class="_3_7SH _3DFk6 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">TEXT TO COPY IS ME</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>
<div class="_3_7SH _3DFk6123456 message-in">
<div class="Tkt2p">
<div class="copyable-text" data-pre-plain-text="[10:26 AM, 5/28/2019] יוסף צדוק: ">
<div class="_3zb-j ZhF0n">
<span dir="rtl" class="XELVh selectable-text invisible-space copyable-text">New text</span></div></div>
<div class="_2f-RV"><div class="_1DZAH">
<span class="_1ORuP">
</span><span class="_3EFt_">10:26 AM</span></div></div></div><span></span></div>
'''

soup = BeautifulSoup(html_con)

content_message_in= soup.find_all('div', {'class': 'message-in'})
span_content =[x.find_all('span') for x in content_message_in]
span_text  = [x[0].get_text() for x in span_content]

#o/p
['TEXT TO COPY IS ME', 'New text']


问:
Ruby: require 'irbtools' raises LoadError
I installed the irbtools gem, but I can't require it.

```<code>$ sudo gem1.9.1 install irbtools
Successfully installed irbtools-0.8.7
1 gem installed
Installing ri documentation for irbtools-0.8.7...
Building YARD (yri) index for irbtools-0.8.7...
Installing RDoc documentation for irbtools-0.8.7...

$ gem1.9.1 which irbtools  # yup, installed OK
/var/lib/gems/1.9.1/gems/irbtools-0.8.7/lib/irbtools.rb

$ ls /var/lib/gems/1.9.1/gems/irbtools-0.8.7/lib/
irbtools  irbtools.rb

$ ruby1.9.1 -e 'require "irbtools"'
<internal:lib/rubygems/custom_require>:33:in `require': no such file to load -- irbtools (LoadError)
    from <internal:lib/rubygems/custom_require>:33:in `rescue in require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from -e:1:in `<main>'
</code>```

It doesn't work in irb1.9.1 either.  All other gems in /var/lib/gems/1.9.1/gem seem to be working fine.  Now I'm kinda dumbstruck.

Can anyone please help me track down what's going on?  I'm not necessarily looking for a solution, but just an idea what to do to debug the problem.

I'm on Debian Squeeze with

```<code>$ ruby1.9.1 --version
ruby 1.9.2p180 (2011-02-18 revision 30909) [i486-linux]
</code>```

答:
This error is quite strange... I haven't got a debian here, but a generic solution would be to use rvm or build ruby from source.

Hints for debugging the problem:

Does requiering or loading /var/lib/gems/1.9.1/gems/irbtools-0.8.7/lib/irbtools.rb directly work?

Do your ruby binary and your gem binary really refer to the same installation?

Can irbtools be found with the Gem.source_index method?: Gem.source_index.gems.keys.grep /irbtools/

Body:
I installed the irbtools gem, but I can't require it.

$ sudo gem1.9.1 install irbtools
Successfully installed irbtools-0.8.7
1 gem installed
Installing ri documentation for irbtools-0.8.7...
Building YARD (yri) index for irbtools-0.8.7...
Installing RDoc documentation for irbtools-0.8.7...

$ gem1.9.1 which irbtools  # yup, installed OK
/var/lib/gems/1.9.1/gems/irbtools-0.8.7/lib/irbtools.rb

$ ls /var/lib/gems/1.9.1/gems/irbtools-0.8.7/lib/
irbtools  irbtools.rb

$ ruby1.9.1 -e 'require "irbtools"'
<internal:lib/rubygems/custom_require>:33:in `require': no such file to load -- irbtools (LoadError)
    from <internal:lib/rubygems/custom_require>:33:in `rescue in require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from -e:1:in `'

It doesn't work in irb1.9.1 either.  All other gems in /var/lib/gems/1.9.1/gem seem to be working fine.  Now I'm kinda dumbstruck.

Can anyone please help me track down what's going on?  I'm not necessarily looking for a solution, but just an idea what to do to debug the problem.

I'm on Debian Squeeze with

$ ruby1.9.1 --version
ruby 1.9.2p180 (2011-02-18 revision 30909) [i486-linux]


问:
How do I make the submenus stay at top?
I am developing a Magento2 webshop, I have bought a theme to use, but I want to change the look of the megamenu so that the submenu fills the same height as the original menu and so that the submenu starts at the top of the menu and not at the top of the list.

答:
Maybe you could share some of the code (in a codepen or something similar) so I can see the structure. But here's a snippet of what I think you want to achieve.
https://codepen.io/europarising/pen/xNJqVj</p>

```<code> .categories {
   display: flex;
   flex-direction: row;
   flex-wrap: wrap;
   align-self: flex-start;
   border: 2px solid red;
   padding: 10px;
   width: 1000px;
   height: 300px;
   overflow: hidden;
   overflow-y: auto;
 }

 .categories__layer1 {
   list-style: none;
   padding: 0;
   margin: 0 0 20px 0;
 }

 .categories .categories__layer1 > li {
   display: flex;
   flex-direction: column;
   flex-wrap: nowrap;
   align-self: flex-start;
   padding-right: 20px;
 }

 .categories .categories__layer1 > li span {
   font-weight: bold;
 }

 .categories__layer2 {
   display: flex;
   flex-direction: column;
   flex-wrap: wrap;
   align-self: flex-start;
   list-style: none;
   padding: 0;
   margin: 0 0 20px 0;
 }
</code>```

Title: How do I make the submenus stay at top?

Body:
Maybe you could share some of the code (in a codepen or something similar) so I can see the structure. But here's a snippet of what I think you want to achieve.
https://codepen.io/europarising/pen/xNJqVj

 .categories {
   display: flex;
   flex-direction: row;
   flex-wrap: wrap;
   align-self: flex-start;
   border: 2px solid red;
   padding: 10px;
   width: 1000px;
   height: 300px;
   overflow: hidden;
   overflow-y: auto;
 }

 .categories__layer1 {
   list-style: none;
   padding: 0;
   margin: 0 0 20px 0;
 }

 .categories .categories__layer1 > li {
   display: flex;
   flex-direction: column;
   flex-wrap: nowrap;
   align-self: flex-start;
   padding-right: 20px;
 }

 .categories .categories__layer1 > li span {
   font-weight: bold;
 }

 .categories__layer2 {
   display: flex;
   flex-direction: column;
   flex-wrap: wrap;
   align-self: flex-start;
   list-style: none;
   padding: 0;
   margin: 0 0 20px 0;
 }


问:
How to compile with VS2017 for an older C++ standard?
I am using Visual Studio 2017 and need to create code that is compatible to VS2008 (C++03 or C++98). Is there a switch to restrict MSVC to C++03 features?

I am using CMake and tried to set

```<code>set_property(TARGET tgt PROPERTY CXX_STANDARD 98)
</code>```

But this seems only to make sure, that the compiler supports C++98 or newer.

Any solution, that checks if C++ code uses features that are newer than the features supported by VS2008 will work as well. I just need to make sure, that I do not accidentally use features that are too new.

答:
MSVC only got the standard switch in one of the updates to VS2015 (Update 3 to be exact) which was more or less C++14 compliant, and as such there are only switches for standards starting with C++14 (plus a few later features that were already implemented at the time of the update). All older features are enabled unconditionally for backwards compatibility (and because of all the work required to retrofit already implemented features for previous standards for virtually no gain).

See this blog post for more information: https://devblogs.microsoft.com/cppblog/standards-version-switches-in-the-compiler/

Also, note that there were a lot of conformance improvements in newer versions of MSVC, so even with the std switches you could write code that wouldn't work or would behave differently on older compiler.

A better solution would be just to use VS2008 toolset from VS2017 visual studio, as explained here: https://devblogs.microsoft.com/cppblog/stuck-on-an-older-toolset-version-move-to-visual-studio-2015-without-upgrading-your-toolset/

That way you'll be certain your code compiles on the older toolset, while using up-to-date IDE.

Body:
I am using Visual Studio 2017 and need to create code that is compatible to VS2008 (C++03 or C++98). Is there a switch to restrict MSVC to C++03 features?

I am using CMake and tried to set

set_property(TARGET tgt PROPERTY CXX_STANDARD 98)

But this seems only to make sure, that the compiler supports C++98 or newer.

Any solution, that checks if C++ code uses features that are newer than the features supported by VS2008 will work as well. I just need to make sure, that I do not accidentally use features that are too new.


问:
How to change row background color dynamic in MVC view?
I have a dynamic table like:

```<code><tbody>
  <% foreach (var item in Model)
   {
  %>
      <tr>
       ......
      </tr>
  <% } %>
</tbody>
</code>```

Then I want to change the row background color to different for neighbor row:

```<code><tbody>
     <% int i = 0;
        foreach (var item in Model)
        {
     %>
     <%if (i++ % 2 == 0)
     { %>
       <tr style="background-color:Aqua">
     <%} else { %>
       <tr style="background-color:Fuchsia">
     <%} %>
     ....
      </tr>
  <% } %>
</tbody>
</code>```

But it doesn't work.  Or anotther way like: <tr style="background-color:<%...%>">, also not work. How to resolve this problem?

答:
You can use bootstrap class - table table-striped

e.g.-

```<code><table class="table table-striped">
.....
</table>
</code>```

Body:
I have a dynamic table like:

  <% foreach (var item in Model)
   {
  %>

       ......

  <% } %>

Then I want to change the row background color to different for neighbor row:

     <% int i = 0;
        foreach (var item in Model)
        {
     %>
     <%if (i++ % 2 == 0)
     { %>

     <%} else { %>

     <%} %>
     ....

  <% } %>

But it doesn't work.  Or anotther way like: <tr style="background-color:<%...%>">, also not work. How to resolve this problem?

Body:
You can use bootstrap class - table table-striped

e.g.-

<table class="table table-striped">
.....
</table>


问:
Extract string value of an ENUM in a Typescript Object
I have an Enum:

```<code>export enum DistanceMeasure {
Miles, Kilometers
</code>```

}

To use in a user object:

```<code>export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff
</code>```

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

```<code>      console.log(user.DistanceMeasure);
</code>```

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

```<code>      console.log(user.DistanceMeasure[0]);
</code>```

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

答:
Since you have not explicity defined the values for your enums so they have got default values of 0 and 1. Now you are getting 0 and 1 from server, so that maps correctly to the enum. What you do is to write a pipe to format 0 as "Mile" and 1 as "Kilometer".

```<code>@Pipe({
  name: 'unit'
})
export class UnitPipe implements PipeTransform {

  constructor() {
  }
  transform(value: DistanceMeasure ): any {
    return value === DistanceMeasure.Mile ? 'Mile' : 'Kilometer'
  }

}
</code>```

And in your html use it like this

```<code>{{ user.DistanceMeasure | unit }}

</code>```

Body:
I have an Enum:

export enum DistanceMeasure {
Miles, Kilometers

}

To use in a user object:

export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

      console.log(user.DistanceMeasure);

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

      console.log(user.DistanceMeasure[0]);

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

Body:
Since you have not explicity defined the values for your enums so they have got default values of 0 and 1. Now you are getting 0 and 1 from server, so that maps correctly to the enum. What you do is to write a pipe to format 0 as "Mile" and 1 as "Kilometer".

@Pipe({
  name: 'unit'
})
export class UnitPipe implements PipeTransform {

  constructor() {
  }
  transform(value: DistanceMeasure ): any {
    return value === DistanceMeasure.Mile ? 'Mile' : 'Kilometer'
  }

}

And in your html use it like this

{{ user.DistanceMeasure | unit }}


问:
vim + janus / indent a perl block
using vim + janus (https://github.com/carlhuda/janus)
is enabled by default  in .vim/vimrc

filetype plugin indent on

i'm writing perl, every newline is indented by default.

how i can select a block (or the full document) and
reindent automatically?

答: You can select the block by going to visual mode (press v or Shift + v or Ctrl + v in normal mode). Reindent can be done pressing = after selection of the block.

Title: vim + janus / indent a perl block


问:
Drawing an Edge (Line) Between Two Nodes ( Circles)
I am working on a dependancy graph that consists of multiple nodes and multiple directed edges from one node to another in the graph.

I am trying to draw a visualation of the graph by adding n number of nodes as circles and edges between those nodes as a line.

I a using Graphics library of Java along with JPanel and Jframe.

This is currently the code I have made:

```<code>public class LoopUnrolling extends JPanel{

static int length = 5;
static String graph[][] = new String[length][length];

@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);

    Random random = new Random();

    int x1 = random.nextInt(500);
    int y1 = random.nextInt(100);

    int x2 = random.nextInt(500);
    int y2 = random.nextInt(100);

    g.setColor(Color.red);
    g.drawOval(x1,y1,30,40);
    g.drawOval(x2,y2,30,40);
    g.drawLine(x1, y1, x2, y2);

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

         LoopUnrolling paintObject = new LoopUnrolling();
         JFrame jf = new JFrame();
         jf.setTitle("Dependancy Graph");
         jf.setSize(600,400);
         jf.setVisible(true);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.add(paintObject);
        }

 }
</code>```

I was able to draw two circles and a line but the problem  I am getting is connecting those two circles with an edge.

I have drawn each node at a random place on the canvas and want to add a Line  between those two nodes.
The line has Point1(x1,y1) and Point2(x2,y2). These points should be the points on two different Node's(Circles) outline

答:
You have two ellipses with centers

```<code> cx1 = x1 + w1/2, cy1 = y1 + h1/2
 and
 cx2 = x2 + w2/2, cy2 = y2 + h2/2
</code>```

where wxx and hxx are width and height of ellipse (third and fourth parameters of drawOval)

Get difference vector

```<code> dx = cx2 - cx1
 dy = cy2 - cy1
</code>```

Normalize it

```<code> len  = sqrt(dx*dx + dy*dy)
 dx = dx / len
 dy = dy / len
</code>```

Now calculate points at circumference

```<code> r1 = 0.5 * w1 * h1 / sqrt(w1*w1*dy*dy+h1*h1*dx*dx)
 px1 = cx1 + r1 * dx
 py1 = cy1 + r1 * dy

 r2 = 0.5 * w2 * h2 / sqrt(w2*w2*dy*dy+h2*h2*dx*dx)
 px2 = cx2 - r2 * dx
 py2 = cy2 - r2 * dy
</code>```

And draw line segment (px1,py1)-(px2,py2)

Sample Delphi implementation and result:

Body:
I am working on a dependancy graph that consists of multiple nodes and multiple directed edges from one node to another in the graph.

I am trying to draw a visualation of the graph by adding n number of nodes as circles and edges between those nodes as a line.

I a using Graphics library of Java along with JPanel and Jframe.

This is currently the code I have made:

public class LoopUnrolling extends JPanel{

static int length = 5;
static String graph[][] = new String[length][length];

@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);

    Random random = new Random();

    int x1 = random.nextInt(500);
    int y1 = random.nextInt(100);

    int x2 = random.nextInt(500);
    int y2 = random.nextInt(100);

    g.setColor(Color.red);
    g.drawOval(x1,y1,30,40);
    g.drawOval(x2,y2,30,40);
    g.drawLine(x1, y1, x2, y2);

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

         LoopUnrolling paintObject = new LoopUnrolling();
         JFrame jf = new JFrame();
         jf.setTitle("Dependancy Graph");
         jf.setSize(600,400);
         jf.setVisible(true);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.add(paintObject);
        }

 }

I was able to draw two circles and a line but the problem  I am getting is connecting those two circles with an edge.

I have drawn each node at a random place on the canvas and want to add a Line  between those two nodes.
The line has Point1(x1,y1) and Point2(x2,y2). These points should be the points on two different Node's(Circles) outline

Body:
You have two ellipses with centers

 cx1 = x1 + w1/2, cy1 = y1 + h1/2
 and
 cx2 = x2 + w2/2, cy2 = y2 + h2/2

where wxx and hxx are width and height of ellipse (third and fourth parameters of drawOval)

Get difference vector

 dx = cx2 - cx1
 dy = cy2 - cy1

Normalize it

 len  = sqrt(dx*dx + dy*dy)
 dx = dx / len
 dy = dy / len

Now calculate points at circumference

 r1 = 0.5 * w1 * h1 / sqrt(w1*w1*dy*dy+h1*h1*dx*dx)
 px1 = cx1 + r1 * dx
 py1 = cy1 + r1 * dy

 r2 = 0.5 * w2 * h2 / sqrt(w2*w2*dy*dy+h2*h2*dx*dx)
 px2 = cx2 - r2 * dx
 py2 = cy2 - r2 * dy

And draw line segment (px1,py1)-(px2,py2)

Sample Delphi implementation and result:


答:
Could it be that when you are getting the spans, you are using

```<code>find_element_by_xpath
</code>```

instead of

```<code>find_elements_by_xpath
</code>```

So its just returning the first element that matches, every time.

see the answer for this question:
https://sqa.stackexchange.com/questions/37380/find-elements-by-xpath-issue?answertab=votes#tab-top

Title: Find elemtnt*s* return array with same element

Body:
Could it be that when you are getting the spans, you are using

find_element_by_xpath

instead of

find_elements_by_xpath

So its just returning the first element that matches, every time.

see the answer for this question:
https://sqa.stackexchange.com/questions/37380/find-elements-by-xpath-issue?answertab=votes#tab-top


问:
How can I identify only base tables when iterating through all tables in SQL smo?
This is my code:

```<code>Server server = new Server(new ServerConnection(con));
server.ConnectionContext.Connect();

foreach (Table table in server.Databases[sqlDatabase].Tables)
{
    if (table <is a base table>)
</code>```

Basically this pulls back views as well I think. The SQL I use to identify the wanted tables is:

SELECT TABLE_NAME FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

However there doesn't seem to be a TABLE_TYPE property on the results which are Microsoft.SqlServer.Management.Smo.TableCollection. According to SQL, the TABLE_TYPE is either BASE TABLE or VIEW so only two possibilities.

How can I identify only tables (and not views)?

答:
Looping over the TablesCollection will not enumerate the Views, so your code should works as it is without worrying about Views.

Indeed you have a Views collection as server.Databases[sqlDatabase].Views

And, in this collection as well as in the Tables collection, you could differentiate your own views/tables from the system views/tables using the property IsSystemObject

```<code>var myTables = server.Databases[sqlDatabase].Views
                    .Cast<Table> => !v.IsSystemObject));

var myViews = server.Databases[sqlDatabase].Views
                    .Cast<View>().Where(v => !v.IsSystemObject));
</code>```

Body:
This is my code:

Server server = new Server(new ServerConnection(con));
server.ConnectionContext.Connect();

foreach (Table table in server.Databases[sqlDatabase].Tables)
{
    if (table <is a base table>)

Basically this pulls back views as well I think. The SQL I use to identify the wanted tables is:

SELECT TABLE_NAME FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

However there doesn't seem to be a TABLE_TYPE property on the results which are Microsoft.SqlServer.Management.Smo.TableCollection. According to SQL, the TABLE_TYPE is either BASE TABLE or VIEW so only two possibilities.

How can I identify only tables (and not views)?

Body:
Looping over the TablesCollection will not enumerate the Views, so your code should works as it is without worrying about Views.

Indeed you have a Views collection as server.Databases[sqlDatabase].Views

And, in this collection as well as in the Tables collection, you could differentiate your own views/tables from the system views/tables using the property IsSystemObject

var myTables = server.Databases[sqlDatabase].Views
                    .Cast<Table> => !v.IsSystemObject));

var myViews = server.Databases[sqlDatabase].Views
                    .Cast<View>().Where(v => !v.IsSystemObject));