问:
How to verify if a title contains one value from a string with multiple values separated by "," in Selenium
I have the values in this variable

```<code>private String possibleTitleNames = "Sistem ,PC ,Desktop ";
</code>```

When I go on my method like this:

```<code>checkPageTitle(driver, possibleTitleNames);
</code>```

I want to check if a title contains one value from this String
My method for this is here

```<code>public void checkPageTitle(WebDriver driver, String titles)
    {

    String[] items2 = titles.split(",");
    String[] items1 =getRandomWayStringValues(items2);
    items1 = titles.split(",");
    for(int i=0;i<items2.length;i++){
           boolean found = false;
           for(int j=0;j<items1.length;j++){
              if((items2[i].equals(items1[j]))){
                 found = true;
                 break;
              }
           }

           if (found) {
              Assert.assertTrue(items2[i],driver.getTitle().contains(items2[i]));
              System.out.println(items2[i]);
           } else {
               System.out.println("Elements are not equals");
           }
        }
    }
</code>```

In String [] items1 I want to have these values shuffled and the method for this is right here

```<code>public String[] getRandomWayStringValues(String [] list){

    String[] newValuesList = new String[] {"PC","Desktop","Sistem"};
    List<String> strList = Arrays.asList(newValuesList);
    Collections.shuffle(strList);
    return newValuesList = strList.toArray(new String[strList.size()]);

}
</code>```

My method works when the title contains the word "Sistem" but if I have a title with "Desktop" or "PC" it doesn't work and I think that the getRandom method doesn't do what I want to do

答:
First of all you should have always the same value in items1 and items2 because you do something like:

```<code>String[] items2 = titles.split(",");
String[] items1 = getRandomWayStringValues(items2);  // this is replaced further
items1 = titles.split(",");   // this will replace items1 value
</code>```

You can think about such solution:

```<code>List<String> possibleTitles = Arrays.asList("Sistem", "PC", "Desktop");
...
String title = "You title here with PC or whatever";

for(String possibleTitle : possibleTitles) {
    if(title.contains(possibleTitle)) {
        assertTrue(driver.getTitle().contains(possibleTitle));
    }
}

fail();
</code>```

Body:
I have the values in this variable

private String possibleTitleNames = "Sistem ,PC ,Desktop ";

When I go on my method like this:

checkPageTitle(driver, possibleTitleNames);

I want to check if a title contains one value from this String
My method for this is here

public void checkPageTitle(WebDriver driver, String titles)
    {

    String[] items2 = titles.split(",");
    String[] items1 =getRandomWayStringValues(items2);
    items1 = titles.split(",");
    for(int i=0;i<items2.length;i++){
           boolean found = false;
           for(int j=0;j<items1.length;j++){
              if((items2[i].equals(items1[j]))){
                 found = true;
                 break;
              }
           }

           if (found) {
              Assert.assertTrue(items2[i],driver.getTitle().contains(items2[i]));
              System.out.println(items2[i]);
           } else {
               System.out.println("Elements are not equals");
           }
        }
    }

In String [] items1 I want to have these values shuffled and the method for this is right here

public String[] getRandomWayStringValues(String [] list){

    String[] newValuesList = new String[] {"PC","Desktop","Sistem"};
    List<String> strList = Arrays.asList(newValuesList);
    Collections.shuffle(strList);
    return newValuesList = strList.toArray(new String[strList.size()]);

}

My method works when the title contains the word "Sistem" but if I have a title with "Desktop" or "PC" it doesn't work and I think that the getRandom method doesn't do what I want to do

Body:
First of all you should have always the same value in items1 and items2 because you do something like:

String[] items2 = titles.split(",");
String[] items1 = getRandomWayStringValues(items2);  // this is replaced further
items1 = titles.split(",");   // this will replace items1 value

You can think about such solution:

List<String> possibleTitles = Arrays.asList("Sistem", "PC", "Desktop");
...
String title = "You title here with PC or whatever";

for(String possibleTitle : possibleTitles) {
    if(title.contains(possibleTitle)) {
        assertTrue(driver.getTitle().contains(possibleTitle));
    }
}

fail();


来源: stackexchange

问:
how to determine sizeof class with virtual functions?
this is kind of homework question. For the following code,

```<code>#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}
</code>```

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

答:
Forgive me for being vague, but you are mentioning that it is homework in nature.

See what sizeof() returns for the other classes.  Your answer will vary depending on your compiler and whether you are in a 32 or 64 bit environment.

Happy sleuthing!

ContentLicense: CC BY-SA 3.0

Body:
this is kind of homework question. For the following code,

#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

ContentLicense: CC BY-SA 2.5


问:
Why does Guava Enums.ifPresent use synchronized under the hood?
Guava's Enums.ifPresent(Class, String) calls Enums.getEnumConstants under the hood:

```<code>@GwtIncompatible // java.lang.ref.WeakReference
static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
Class<T> enumClass) {
    synchronized (enumConstantCache) {
        Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass);
        if (constants == null) {
            constants = populateCache(enumClass);
        }
        return constants;
    }
}
</code>```

Why does it need a synchronized block? Wouldn't that incur a <s>heavy</s> performance penalty? Java's Enum.valueOf(Class, String) does not appear to need one. Further on if synchronization is indeed necessary, why do it so inefficiently? One would hope if enum is present in cache, it can be retrieved without locking. Only lock if cache needs to be populated.

For Reference: Maven Dependency

```<code><dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.2-jre</version>
</dependency>
</code>```

Edit: By locking I'm referring to a double checking lock.

答:
I've accepted @maaartinus answer, but wanted to write a separate "answer" about the circumstances behind the question and the interesting rabbit hole it lead me to.

tl;dr - Use Java's Enum.valueOf which is thread safe and does not sync unlike Guava's Enums.ifPresent. Also in majority of cases it probably doesn't matter.

Long story:

I'm working on a codebase that utilizes light weight java threads Quasar Fibers. In order to harness the power of Fibers, the code they run should be primarily async and non-blocking because Fibers are multiplexed to Java/OS Threads. It becomes very important that individual Fibers do not "block" the underlying thread. If underlying thread is blocked, it will block all Fibers running on it and performance degrades considerably. Guava's Enums.ifPresent is one of those blockers and I'm certain it can be avoided.

Initially, I started using Guava's Enums.ifPresent because it returns null on invalid enum values. Unlike Java's Enum.valueOf which throws IllegalArgumentException (which to my taste is less preferrable than a null value).

Here is a crude benchmark comparing various methods of converting to enums:

Java's Enum.valueOf with catching IllegalArgumentException to return null

Guava's Enums.ifPresent

Apache Commons Lang EnumUtils.getEnum

Apache Commons Lang 3 EnumUtils.getEnum

My Own Custom Immutable Map Lookup

Notes:

Apache Common Lang 3 uses Java's Enum.valueOf under the hood and are hence identical

Earlier version of Apache Common Lang uses a very similar WeakHashMap solution to Guava but does not use synchronization. They favor cheap reads and more expensive writes (my knee jerk reaction says that's how Guava should have done it)

Java's decision to throw IllegalArgumentException is likely to have a small cost associated with it when dealing with invalid enum values. Throwing/catching exceptions isn't free.

Guava is the only method here that uses synchronization

Benchmark Setup:

uses an ExecutorService with a fixed thread pool of 10 threads

submits 100K Runnable tasks to convert enums

each Runnable task converts 100 enums

each method of converting enums will convert 10 million strings (100K x 100)

Benchmark Results from a run:

```<code>Convert valid enum string value:
    JAVA -> 222 ms
    GUAVA -> 964 ms
    APACHE_COMMONS_LANG -> 138 ms
    APACHE_COMMONS_LANG3 -> 149 ms
    MY_OWN_CUSTOM_LOOKUP -> 160 ms

Try to convert INVALID enum string value:
    JAVA -> 6009 ms
    GUAVA -> 734 ms
    APACHE_COMMONS_LANG -> 65 ms
    APACHE_COMMONS_LANG3 -> 5558 ms
    MY_OWN_CUSTOM_LOOKUP -> 92 ms
</code>```

These numbers should be taken with a heavy grain of salt and will change depending on other factors. But they were good enough for me to conclude to go with Java's solution for the codebase using Fibers.

Benchmark Code:

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Enums;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;

public class BenchmarkEnumValueOf {

    enum Strategy {
        JAVA,
        GUAVA,
        APACHE_COMMONS_LANG,
        APACHE_COMMONS_LANG3,
        MY_OWN_CUSTOM_LOOKUP;

        private final static ImmutableMap<String, Strategy> lookup;

        static {
            Builder<String, Strategy> immutableMapBuilder = ImmutableMap.builder();
            for (Strategy strategy : Strategy.values()) {
                immutableMapBuilder.put(strategy.name(), strategy);
            }

            lookup = immutableMapBuilder.build();
        }

        static Strategy toEnum(String name) {
            return name != null ? lookup.get(name) : null;
        }
    }

    public static void main(String[] args) {
        final int BENCHMARKS_TO_RUN = 1;

        System.out.println("Convert valid enum string value:");
        for (int i = 0; i < BENCHMARKS_TO_RUN; i++) {
            for (Strategy strategy : Strategy.values()) {
                runBenchmark(strategy, "JAVA", 100_000);
            }
        }

        System.out.println("\nTry to convert INVALID enum string value:");
        for (int i = 0; i < BENCHMARKS_TO_RUN; i++) {
            for (Strategy strategy : Strategy.values()) {
                runBenchmark(strategy, "INVALID_ENUM", 100_000);
            }
        }
    }

    static void runBenchmark(Strategy strategy, String enumStringValue, int iterations) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        long timeStart = System.currentTimeMillis();

        for (int i = 0; i < iterations; i++) {
            executorService.submit(new EnumValueOfRunnable(strategy, enumStringValue));
        }

        executorService.shutdown();

        try {
            executorService.awaitTermination(1000, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        long timeDuration = System.currentTimeMillis() - timeStart;

        System.out.println("\t" + strategy.name() + " -> " + timeDuration + " ms");
    }

    static class EnumValueOfRunnable implements Runnable {

        Strategy strategy;
        String enumStringValue;

        EnumValueOfRunnable(Strategy strategy, String enumStringValue) {
            this.strategy = strategy;
            this.enumStringValue = enumStringValue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                switch (strategy) {
                    case JAVA:
                        try {
                            Enum.valueOf(Strategy.class, enumStringValue);
                        } catch (IllegalArgumentException e) {}
                        break;
                    case GUAVA:
                        Enums.getIfPresent(Strategy.class, enumStringValue);
                        break;
                    case APACHE_COMMONS_LANG:
                        org.apache.commons.lang.enums.EnumUtils.getEnum(Strategy.class, enumStringValue);
                        break;
                    case APACHE_COMMONS_LANG3:
                        org.apache.commons.lang3.EnumUtils.getEnum(Strategy.class, enumStringValue);
                        break;
                    case MY_OWN_CUSTOM_LOOKUP:
                        Strategy.toEnum(enumStringValue);
                        break;
                }
            }
        }
    }

}
</code>```

Body:
Guava's Enums.ifPresent(Class, String) calls Enums.getEnumConstants under the hood:

@GwtIncompatible // java.lang.ref.WeakReference
static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
Class<T> enumClass) {
    synchronized (enumConstantCache) {
        Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass);
        if (constants == null) {
            constants = populateCache(enumClass);
        }
        return constants;
    }
}

Why does it need a synchronized block? Wouldn't that incur a <s>heavy</s> performance penalty? Java's Enum.valueOf(Class, String) does not appear to need one. Further on if synchronization is indeed necessary, why do it so inefficiently? One would hope if enum is present in cache, it can be retrieved without locking. Only lock if cache needs to be populated.

For Reference: Maven Dependency

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.2-jre</version>
</dependency>

Edit: By locking I'm referring to a double checking lock.

Body:
I've accepted @maaartinus answer, but wanted to write a separate "answer" about the circumstances behind the question and the interesting rabbit hole it lead me to.

tl;dr - Use Java's Enum.valueOf which is thread safe and does not sync unlike Guava's Enums.ifPresent. Also in majority of cases it probably doesn't matter.

Long story:

I'm working on a codebase that utilizes light weight java threads Quasar Fibers. In order to harness the power of Fibers, the code they run should be primarily async and non-blocking because Fibers are multiplexed to Java/OS Threads. It becomes very important that individual Fibers do not "block" the underlying thread. If underlying thread is blocked, it will block all Fibers running on it and performance degrades considerably. Guava's Enums.ifPresent is one of those blockers and I'm certain it can be avoided.

Initially, I started using Guava's Enums.ifPresent because it returns null on invalid enum values. Unlike Java's Enum.valueOf which throws IllegalArgumentException (which to my taste is less preferrable than a null value).

Here is a crude benchmark comparing various methods of converting to enums:

Java's Enum.valueOf with catching IllegalArgumentException to return null

Guava's Enums.ifPresent

Apache Commons Lang EnumUtils.getEnum

Apache Commons Lang 3 EnumUtils.getEnum

My Own Custom Immutable Map Lookup

Notes:

Apache Common Lang 3 uses Java's Enum.valueOf under the hood and are hence identical

Earlier version of Apache Common Lang uses a very similar WeakHashMap solution to Guava but does not use synchronization. They favor cheap reads and more expensive writes (my knee jerk reaction says that's how Guava should have done it)

Java's decision to throw IllegalArgumentException is likely to have a small cost associated with it when dealing with invalid enum values. Throwing/catching exceptions isn't free.

Guava is the only method here that uses synchronization

Benchmark Setup:

uses an ExecutorService with a fixed thread pool of 10 threads

submits 100K Runnable tasks to convert enums

each Runnable task converts 100 enums

each method of converting enums will convert 10 million strings (100K x 100)

Benchmark Results from a run:

Convert valid enum string value:
    JAVA -> 222 ms
    GUAVA -> 964 ms
    APACHE_COMMONS_LANG -> 138 ms
    APACHE_COMMONS_LANG3 -> 149 ms
    MY_OWN_CUSTOM_LOOKUP -> 160 ms

Try to convert INVALID enum string value:
    JAVA -> 6009 ms
    GUAVA -> 734 ms
    APACHE_COMMONS_LANG -> 65 ms
    APACHE_COMMONS_LANG3 -> 5558 ms
    MY_OWN_CUSTOM_LOOKUP -> 92 ms

These numbers should be taken with a heavy grain of salt and will change depending on other factors. But they were good enough for me to conclude to go with Java's solution for the codebase using Fibers.

Benchmark Code:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Enums;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;

public class BenchmarkEnumValueOf {

    enum Strategy {
        JAVA,
        GUAVA,
        APACHE_COMMONS_LANG,
        APACHE_COMMONS_LANG3,
        MY_OWN_CUSTOM_LOOKUP;

        private final static ImmutableMap<String, Strategy> lookup;

        static {
            Builder<String, Strategy> immutableMapBuilder = ImmutableMap.builder();
            for (Strategy strategy : Strategy.values()) {
                immutableMapBuilder.put(strategy.name(), strategy);
            }

            lookup = immutableMapBuilder.build();
        }

        static Strategy toEnum(String name) {
            return name != null ? lookup.get(name) : null;
        }
    }

    public static void main(String[] args) {
        final int BENCHMARKS_TO_RUN = 1;

        System.out.println("Convert valid enum string value:");
        for (int i = 0; i < BENCHMARKS_TO_RUN; i++) {
            for (Strategy strategy : Strategy.values()) {
                runBenchmark(strategy, "JAVA", 100_000);
            }
        }

        System.out.println("\nTry to convert INVALID enum string value:");
        for (int i = 0; i < BENCHMARKS_TO_RUN; i++) {
            for (Strategy strategy : Strategy.values()) {
                runBenchmark(strategy, "INVALID_ENUM", 100_000);
            }
        }
    }

    static void runBenchmark(Strategy strategy, String enumStringValue, int iterations) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        long timeStart = System.currentTimeMillis();

        for (int i = 0; i < iterations; i++) {
            executorService.submit(new EnumValueOfRunnable(strategy, enumStringValue));
        }

        executorService.shutdown();

        try {
            executorService.awaitTermination(1000, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        long timeDuration = System.currentTimeMillis() - timeStart;

        System.out.println("\t" + strategy.name() + " -> " + timeDuration + " ms");
    }

    static class EnumValueOfRunnable implements Runnable {

        Strategy strategy;
        String enumStringValue;

        EnumValueOfRunnable(Strategy strategy, String enumStringValue) {
            this.strategy = strategy;
            this.enumStringValue = enumStringValue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                switch (strategy) {
                    case JAVA:
                        try {
                            Enum.valueOf(Strategy.class, enumStringValue);
                        } catch (IllegalArgumentException e) {}
                        break;
                    case GUAVA:
                        Enums.getIfPresent(Strategy.class, enumStringValue);
                        break;
                    case APACHE_COMMONS_LANG:
                        org.apache.commons.lang.enums.EnumUtils.getEnum(Strategy.class, enumStringValue);
                        break;
                    case APACHE_COMMONS_LANG3:
                        org.apache.commons.lang3.EnumUtils.getEnum(Strategy.class, enumStringValue);
                        break;
                    case MY_OWN_CUSTOM_LOOKUP:
                        Strategy.toEnum(enumStringValue);
                        break;
                }
            }
        }
    }

}


问:
Visual Studio Community 2017, ASP.Net and NET Core - No Core Project Templates Available
I've just installed Visual Studio 2017 as well as the NET Core 2.0 SDK.

When I come to create a new ASP.Net Core Web project, the only option I have available to me is the "ASP.NET Web Application (.NET Framework)" however various tutorials and Microsoft guides refer to other project templates available with this exact setup.

In fact, no "NET Core" project templates are present within the New Project form.

Any clues please?

答: Did you install: .NET Core Cross-platform development module?


问:
Getting the next item in a python for loop
I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list:

```<code>for string in tr[30].strings:
      if string == 'X':
              print(string)
              print(string.next())
</code>```

Getting error:

TypeError: 'NavigableString' object is not callable

答:
You can use enumerate, example:

```<code>strings = tr[30].strings

for index, string in enumerate(strings):
    if string == 'X':
        print(string)
        print(strings[index + 1])
</code>```

Body:
I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list:

for string in tr[30].strings:
      if string == 'X':
              print(string)
              print(string.next())

Getting error:

TypeError: 'NavigableString' object is not callable

Body:
You can use enumerate, example:

strings = tr[30].strings

for index, string in enumerate(strings):
    if string == 'X':
        print(string)
        print(strings[index + 1])


问:
Ways to make maven build faster?
I have a multi module java project. Maven takes almost around 40 secs to build it. I have tried maven with multi threaded builds too by specifying -T and -C args for no of threads and cores to be used. But I haven't seen any significant improvement in wall time of my builds.

I am using maven 3.2.3 and sometimes I need to build my project very frequently.

I know that clean goal take a lot of time but I can not omit it.

Suggestions please....

EDIT:

Note:  In my case clean is not taking much time. It finishes in 1 sec. install is taking rest of the time.

答:
You can do a hacky way if you have some extra RAM as I do, and you don't need SSD, because it's sensitive for SSD to do a lot of read-writes. Even if you disable +a bit (MacOS - I don't remember if Win have similar issue). But

create RAM drive (number of ways depends on your OS) and mount it to /Users/Username/volatile folder

locate maven-module-builder-X.X.X.jar in MVN_HOME/lib

in JAR modify file org/apache/maven/model/pom-4.0.0.xml by modifying

<build><directory>/Users/Username/volatile/${project.groupId}/${project.artifactId}/${project.version}/target

From now on all project compilations will be done in memory. And it's a difference even in comparison with SSD.

Yes, its hack and some maven plugins can stop working BTW.

Title: Ways to make maven build faster?

Body:
You can do a hacky way if you have some extra RAM as I do, and you don't need SSD, because it's sensitive for SSD to do a lot of read-writes. Even if you disable +a bit (MacOS - I don't remember if Win have similar issue). But

create RAM drive (number of ways depends on your OS) and mount it to /Users/Username/volatile folder

locate maven-module-builder-X.X.X.jar in MVN_HOME/lib

in JAR modify file org/apache/maven/model/pom-4.0.0.xml by modifying

&lt;build>&lt;directory>/Users/Username/volatile/${project.groupId}/${project.artifactId}/${project.version}/target

From now on all project compilations will be done in memory. And it's a difference even in comparison with SSD.

Yes, its hack and some maven plugins can stop working BTW.

ContentLicense: CC BY-SA 4.0


问:
How to consume all messages required in a Spring IntegrationFlow when message count is greater than the number of concurrent consumers?
I have an integration flow defined like this:

```<code>IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, "queueName")
                    .id("id")
                    .autoStartup(autoStartup)
                    .concurrentConsumers(2)
                    .maxConcurrentConsumers(3)
                    .messageConverter(messageConverter()))
                    .aggregate(a -> a.correlationExpression("payload.entityId")
                                    .releaseExpression("size() eq iterator().next().payload.batchSize")
                                    .sendPartialResultOnExpiry(true)
                                    .groupTimeout(2000)
                                    .expireGroupsUponCompletion(true)
                                    .outputProcessor(myMessageGroupProcessor))
                    .handle(serviceActivatorBean, "myMethod", e -> e.advice(requestHandlerRetryAdviceForIntegrationFlow()))
                    .get();
</code>```

Whose purpose is to group several related messages that are sent in a "batch". Here's an example:

```<code>// Message 1
{ "name": "Message1",
  "entityId": "someId"
  "batchSize": 2,
  "batchIndex": 1,
  .... }

// Message 2
{ "name": "Message2",
  "entityId": "someId"
  "batchSize": 2,
  "batchIndex": 2,
  .... }
</code>```

Due to reasons described here we're using manual ack:ing to RabbitMQ to avoid losing messages.

The integration flow works great for batches of size 2 but as soon as there's more than 2 messages in a batch we run into trouble:

```<code>[my-service] 2017-12-04 17:46:07.966  INFO 1 --- [ask-scheduler-5] x.y.EntityUpdater : Will update entity [entitId] from messages: Message1, Message2
[my-service] 2017-12-04 17:46:09.976  INFO 1 --- [ask-scheduler-3] x.y.EntityUpdater : Will update entity [entitId] from messages: Message3
</code>```

Note that the time between the logged messages is roughly 2 seconds (i.e. what we've confirgured as groupTimeout).

What I suspect the reason for this is is that Spring consumes 2 messages (which are not ack:ed automatically) then the aggregation waits for a 3rd message (since batchSize is 3 in this case). But this message will never be consumed within the 2 second window since there are only two concurrent consumers.

Increasing the concurrentConsumers count to 3 solves this particular issue. The problem is that we don't know the size of the batches that we receive and they could be quite large, perhaps of size 50 or so. This means that simply increasing concurrentConsumers is not a viable option.

What's the appropriate way to handle this in Spring?

答:
As I discussed in the comments to this answer...

When using this pattern, the concurrency * prefetch must be big enough to contain the messages for all outstanding batches.

For this reason, I am not in favor of using the pattern, unless you have fairly predictable data.

Body:
I have an integration flow defined like this:

IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, "queueName")
                    .id("id")
                    .autoStartup(autoStartup)
                    .concurrentConsumers(2)
                    .maxConcurrentConsumers(3)
                    .messageConverter(messageConverter()))
                    .aggregate(a -> a.correlationExpression("payload.entityId")
                                    .releaseExpression("size() eq iterator().next().payload.batchSize")
                                    .sendPartialResultOnExpiry(true)
                                    .groupTimeout(2000)
                                    .expireGroupsUponCompletion(true)
                                    .outputProcessor(myMessageGroupProcessor))
                    .handle(serviceActivatorBean, "myMethod", e -> e.advice(requestHandlerRetryAdviceForIntegrationFlow()))
                    .get();

Whose purpose is to group several related messages that are sent in a "batch". Here's an example:

// Message 1
{ "name": "Message1",
  "entityId": "someId"
  "batchSize": 2,
  "batchIndex": 1,
  .... }

// Message 2
{ "name": "Message2",
  "entityId": "someId"
  "batchSize": 2,
  "batchIndex": 2,
  .... }

Due to reasons described here we're using manual ack:ing to RabbitMQ to avoid losing messages.

The integration flow works great for batches of size 2 but as soon as there's more than 2 messages in a batch we run into trouble:

[my-service] 2017-12-04 17:46:07.966  INFO 1 --- [ask-scheduler-5] x.y.EntityUpdater : Will update entity [entitId] from messages: Message1, Message2
[my-service] 2017-12-04 17:46:09.976  INFO 1 --- [ask-scheduler-3] x.y.EntityUpdater : Will update entity [entitId] from messages: Message3

Note that the time between the logged messages is roughly 2 seconds (i.e. what we've confirgured as groupTimeout).

What I suspect the reason for this is is that Spring consumes 2 messages (which are not ack:ed automatically) then the aggregation waits for a 3rd message (since batchSize is 3 in this case). But this message will never be consumed within the 2 second window since there are only two concurrent consumers.

Increasing the concurrentConsumers count to 3 solves this particular issue. The problem is that we don't know the size of the batches that we receive and they could be quite large, perhaps of size 50 or so. This means that simply increasing concurrentConsumers is not a viable option.

What's the appropriate way to handle this in Spring?


问:
error installing caffe
I am trying to install caffe on my mac. I have installed boost but I get this error:</p>

```<code>make pycaffe -j8
LD -o .build_release/lib/libcaffe.so
clang: warning: argument unused during compilation: '-pthread'
ld: library not found for -lboost_thread-mt
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [.build_release/lib/libcaffe.so] Error 1
</code>```

答:
If you're using anaconda, you can also provide the boost dependency using the conda-forge anaconda channel:

$ conda install -c conda-forge boost

And create the symlinks, as @Marqin said, if they're not available.

The conda-forge boost might soon include the -mt libraries. I opened an issue for it on their github repo.

Title: error installing caffe

Body:
I am trying to install caffe on my mac. I have installed boost but I get this error:

make pycaffe -j8
LD -o .build_release/lib/libcaffe.so
clang: warning: argument unused during compilation: '-pthread'
ld: library not found for -lboost_thread-mt
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [.build_release/lib/libcaffe.so] Error 1


问:
Download multiple files with Firebase
im trying to get 2 files from my firebase storage, they are in a folder called Ara , so the files there are 2  xxx.txt and yyy.txt  (lets call them this way)

so for testing i just run this method

```<code> private void traerPictosFirebase(){

        File localFile = null;
        try {
            localFile = File.createTempFile("xxx","txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        mStorageRef.child("Archivos_Paises/Ara").getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

//here i want to know if i downloaded succefully the file and find the path of it

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });

    }
</code>```

So, now i want to do 2 things, first one is how i know if the file was downloaded to my device, in the onSuccess and second i want to donwload the two files, not just one

thanks

答:
The fact that the onSuccess() callback was even invoked indicates that the file was successfully downloaded.  You don't need any other confirmation.

If you want to download two files, then you'll need to make two calls to getFile() and deal with both of their tasks.

Title: Download multiple files with Firebase

Body:
im trying to get 2 files from my firebase storage, they are in a folder called Ara , so the files there are 2  xxx.txt and yyy.txt  (lets call them this way)

so for testing i just run this method

 private void traerPictosFirebase(){

        File localFile = null;
        try {
            localFile = File.createTempFile("xxx","txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        mStorageRef.child("Archivos_Paises/Ara").getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

//here i want to know if i downloaded succefully the file and find the path of it

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });

    }

So, now i want to do 2 things, first one is how i know if the file was downloaded to my device, in the onSuccess and second i want to donwload the two files, not just one

thanks


问:
Event Handling for UI elements generated from a DataTemplate in UWP
I'm struggling to find out how to respond to any event other than a button click (I can use Command to deal with them).

If create a ToggleSwitch from a DataTemplate how would I generate a "Toggled" event?

答:
Taken from Microsoft documentation ToggleSwitch Class

XAML:

```<code> <StackPanel Orientation="Horizontal">
        <ToggleSwitch Header="Toggle Switch Example"
            OffContent="Do work" OnContent="Working"
            Toggled="ToggleSwitch_Toggled"/>
        <ProgressRing x:Name="progress1"/>
    </StackPanel>
</code>```

Code-Behind:

```<code>private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            ToggleSwitch toggleSwitch = sender as ToggleSwitch;
            if (toggleSwitch != null)
            {
                if (toggleSwitch.IsOn == true)
                {
                    progress1.IsActive = true;
                    progress1.Visibility = Visibility.Visible;
                }
                else
                {
                    progress1.IsActive = false;
                    progress1.Visibility = Visibility.Collapsed;
                }
            }
        }
</code>```

As you can see in XAML you defined a Toggled event handler to handle with to changes in it's state.
The event handler is automatically created in code-behind, and you can add your logic to it.

In this example, you cast your sender object to the ToggleSwitch, which you know was the type of the object which raised this event, and by checking it's properties you can infer for instance if the Switch is On/Off, and handle that state properly, like it is being done in the example above.

Dynamically generated ToggleSwitch with event:

Lets imagine our customers is an ObservableCollection property, which you have defined as the DataContext of your page. Dependending on it's size, we would have the same number of ToggleSwitch showing up on your page, and all of them would redirect to the ToggleSwitch_Toggled.

```<code>         <ListBox ItemsSource="{Binding customers}" Width="350" Margin="0,5,0,10">
            <ListBox.ItemTemplate>
                <DataTemplate>
                   <ToggleSwitch Header="Toggle Switch Example"
                            OffContent="Do work" OnContent="Working"
                            Toggled="ToggleSwitch_Toggled"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</code>```

Is this what you are looking for? It might not be the most useful implementation yet, since there is still no implemented logic in order to understand which of the dynamically created ToggleSwitch raised the event (all call the same eventhandler).

Behaviour:

Body:
Taken from Microsoft documentation ToggleSwitch Class

XAML:

 <StackPanel Orientation="Horizontal">
        <ToggleSwitch Header="Toggle Switch Example"
            OffContent="Do work" OnContent="Working"
            Toggled="ToggleSwitch_Toggled"/>
        <ProgressRing x:Name="progress1"/>
    </StackPanel>

Code-Behind:

private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            ToggleSwitch toggleSwitch = sender as ToggleSwitch;
            if (toggleSwitch != null)
            {
                if (toggleSwitch.IsOn == true)
                {
                    progress1.IsActive = true;
                    progress1.Visibility = Visibility.Visible;
                }
                else
                {
                    progress1.IsActive = false;
                    progress1.Visibility = Visibility.Collapsed;
                }
            }
        }

As you can see in XAML you defined a Toggled event handler to handle with to changes in it's state.
The event handler is automatically created in code-behind, and you can add your logic to it.

In this example, you cast your sender object to the ToggleSwitch, which you know was the type of the object which raised this event, and by checking it's properties you can infer for instance if the Switch is On/Off, and handle that state properly, like it is being done in the example above.

Dynamically generated ToggleSwitch with event:

Lets imagine our customers is an ObservableCollection property, which you have defined as the DataContext of your page. Dependending on it's size, we would have the same number of ToggleSwitch showing up on your page, and all of them would redirect to the ToggleSwitch_Toggled.

         <ListBox ItemsSource="{Binding customers}" Width="350" Margin="0,5,0,10">
            <ListBox.ItemTemplate>
                <DataTemplate>
                   <ToggleSwitch Header="Toggle Switch Example"
                            OffContent="Do work" OnContent="Working"
                            Toggled="ToggleSwitch_Toggled"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Is this what you are looking for? It might not be the most useful implementation yet, since there is still no implemented logic in order to understand which of the dynamically created ToggleSwitch raised the event (all call the same eventhandler).

Behaviour:


问:
How to increase Heap and Perm memory in Jboss?
The real problem is that I don´t know how to increase the Perm size memory base on my RAM memory available on my server.
 I'm in the config file and I can see that I have reserved for the heap memory 8192Mb and MaxPermSize as 1024m.

```<code>JAVA_OPTS="-Xms1024m -Xmx8192m -XX:MaxPermSize=1024m -Djava.net.preferIPv4Stack=true"
JAVA_OPTS="$JAVA_OPTS -Djboss.modules.system.pkgs=$JBOSS_MODULES_SYSTEM_PKGS -Djava.awt.headless=true"
</code>```

The total memory available on my server is 9Gb. As far as I know, the Perm memory space doesn´t belong to the heap memory. I'm using 8Gb for the Heap memory and 1Gb for the Perm.
So, if I want to increase the Perm Memory I will need to reduce the Heap memory, for example to 7GB and then increase the Perm Memory to 2GB, right?
Or I can leave 8Gb for the heap memory and also increase to 2Gb the PermSize.

I'm doing this because I received this error from my server. But I´m not sure what is the problem, because as you can see the Eden space is full but also the PermGen is full.
But the problem can be in the configuration if I have 9GB ram memory available on my server and I have 8Gb reserved for the heap memory and 1 for the perm memory, probably the memory reserved for one space is not fully taken.

```<code>Heap
 PSYoungGen      total 1937408K, used 1119744K [0x0000000755500000, 0x00000007ff680000, 0x0000000800000000)
  eden space 1119744K, 100% used [0x0000000755500000,0x0000000799a80000,0x0000000799a80000)
  from space 817664K, 0% used [0x0000000799a80000,0x0000000799a80000,0x00000007cb900000)
  to   space 811008K, 0% used [0x00000007cde80000,0x00000007cde80000,0x00000007ff680000)
 ParOldGen       total 5592064K, used 5591839K [0x0000000600000000, 0x0000000755500000, 0x0000000755500000)
  object space 5592064K, 99% used [0x0000000600000000,0x00000007554c7ce0,0x0000000755500000)
 PSPermGen       total 261120K, used 260769K [0x00000005c0000000, 0x00000005cff00000, 0x0000000600000000)
  object space 261120K, 99% used [0x00000005c0000000,0x00000005cfea86c8,0x00000005cff00000)
</code>```

答:
You have MaxPermSize=1024m but PSPermGen allocated only 261m, so you don't use all.

Setting Xms differently from Xmx ist usually not good from a performance point of view.

You use all of your physical memory for Heap and PermGen. You should keep some of the memory for the OS. Your server might begin to page.

It might be helpful to analyse the gc-log or use jstat, jconsole or jvisualvm to monitor your memory usage.

Body:
The real problem is that I don´t know how to increase the Perm size memory base on my RAM memory available on my server.
 I'm in the config file and I can see that I have reserved for the heap memory 8192Mb and MaxPermSize as 1024m.

JAVA_OPTS="-Xms1024m -Xmx8192m -XX:MaxPermSize=1024m -Djava.net.preferIPv4Stack=true"
JAVA_OPTS="$JAVA_OPTS -Djboss.modules.system.pkgs=$JBOSS_MODULES_SYSTEM_PKGS -Djava.awt.headless=true"

The total memory available on my server is 9Gb. As far as I know, the Perm memory space doesn´t belong to the heap memory. I'm using 8Gb for the Heap memory and 1Gb for the Perm.
So, if I want to increase the Perm Memory I will need to reduce the Heap memory, for example to 7GB and then increase the Perm Memory to 2GB, right?
Or I can leave 8Gb for the heap memory and also increase to 2Gb the PermSize.

I'm doing this because I received this error from my server. But I´m not sure what is the problem, because as you can see the Eden space is full but also the PermGen is full.
But the problem can be in the configuration if I have 9GB ram memory available on my server and I have 8Gb reserved for the heap memory and 1 for the perm memory, probably the memory reserved for one space is not fully taken.

Heap
 PSYoungGen      total 1937408K, used 1119744K [0x0000000755500000, 0x00000007ff680000, 0x0000000800000000)
  eden space 1119744K, 100% used [0x0000000755500000,0x0000000799a80000,0x0000000799a80000)
  from space 817664K, 0% used [0x0000000799a80000,0x0000000799a80000,0x00000007cb900000)
  to   space 811008K, 0% used [0x00000007cde80000,0x00000007cde80000,0x00000007ff680000)
 ParOldGen       total 5592064K, used 5591839K [0x0000000600000000, 0x0000000755500000, 0x0000000755500000)
  object space 5592064K, 99% used [0x0000000600000000,0x00000007554c7ce0,0x0000000755500000)
 PSPermGen       total 261120K, used 260769K [0x00000005c0000000, 0x00000005cff00000, 0x0000000600000000)
  object space 261120K, 99% used [0x00000005c0000000,0x00000005cfea86c8,0x00000005cff00000)


问:
How to find the first node of the tree in a dict?
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

```<code>              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"
</code>```

the problem is that i dont know how to take it from a dict , because the input is like this :

```<code>{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
</code>```

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

```<code>    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break
</code>```

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

答:
You can use list comprehension:

```<code>d = { "ok":["lol"] , "no":[] , "hi":["ok","no"] , "lol" : [] }
root = [a for a, b in d.items() if all(a not in d for c, d in d.items())][0]
</code>```

Output:

```<code>'hi'
</code>```

Body:
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"

the problem is that i dont know how to take it from a dict , because the input is like this :

{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

Body:
You can use list comprehension:

d = { "ok":["lol"] , "no":[] , "hi":["ok","no"] , "lol" : [] }
root = [a for a, b in d.items() if all(a not in d for c, d in d.items())][0]

Output:

'hi'


问:
I want to create a matlab program that stores and increment the value inside the array after certain events
```<code>for i=1:2

    dice_roll_1=randi(6);
    dice_roll_2=randi(6);
    player_dice_roll=dice_roll_1+dice_roll_2;
    player_position=player_dice_roll;

end
</code>```

For the second round I want the array player_position to have its elements added by the new values of dice_roll_1 and dice_roll_2.

答:
You have to bring the player_position variable outside your loop and initialize it to a value equal to 0. Then, within each loop, you increase it's total value adding the result of the dice rolls:

```<code>player_position = 0;

for i=1:2
    dice_roll_1 = randi(6);
    dice_roll_2 = randi(6);
    player_dice_roll = dice_roll_1+dice_roll_2;
    player_position = player_position + player_dice_roll;
end
</code>```

Body:
for i=1:2

    dice_roll_1=randi(6);
    dice_roll_2=randi(6);
    player_dice_roll=dice_roll_1+dice_roll_2;
    player_position=player_dice_roll;

end

For the second round I want the array player_position to have its elements added by the new values of dice_roll_1 and dice_roll_2.

Body:
You have to bring the player_position variable outside your loop and initialize it to a value equal to 0. Then, within each loop, you increase it's total value adding the result of the dice rolls:

player_position = 0;

for i=1:2
    dice_roll_1 = randi(6);
    dice_roll_2 = randi(6);
    player_dice_roll = dice_roll_1+dice_roll_2;
    player_position = player_position + player_dice_roll;
end


问:
Touch event does not do any action on the Unity c # smartphone
I have this code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Audio;
using UnityEngine.EventSystems;

public class start : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public GameObject musica;
    public bool pulsado;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void OnPointerDown(PointerEventData eventData)
    {
        pulsado = true;
        audio();
        SceneManager.LoadScene("pajaro");
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        pulsado = false;
    }
    void audio()
    {
        musica.SetActive(true);
    }
}
</code>```

When I export it to Android, touch does not work, but if it works in unity

答:
You're using OnPointerDown, this is specific to the mouse, this event does not fire for Touch input (touch input does not have a concept of "up" and "down").

In order to have touch input, you have to use Input.touches during the Update() loop.

Body:
I have this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Audio;
using UnityEngine.EventSystems;

public class start : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public GameObject musica;
    public bool pulsado;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void OnPointerDown(PointerEventData eventData)
    {
        pulsado = true;
        audio();
        SceneManager.LoadScene("pajaro");
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        pulsado = false;
    }
    void audio()
    {
        musica.SetActive(true);
    }
}

When I export it to Android, touch does not work, but if it works in unity


问:
Remove all empty ArrayLists from an ArrayList with Java
I want to go through my ArrayList of ArrayLists and remove all the ones that are empty. Is there a fast and efficient way to do this, other then I guess a for loop?

Example Ouput:

[ [alec, joe, ray], [], [eric, jacob], [] ]

Would then look like this:

[ [alec, joe, ray], [eric, jacob] ]

答:
something like this should suffice.

```<code>nestedArrayList = nestedArrayList.stream()
    .filter(e -> !e.isEmpty())
    .collect(Collectors.toCollection(ArrayList::new));
</code>```

or as Zabuza has suggested, you could use removeIf:

```<code>nestedArrayList.removeIf(ArrayList::isEmpty);
</code>```

IMHO I'd go with the second approach for a couple of reasons but most importantly reading it like "nestedArrayList remove if ArrayList is empty" provides better intent of the code and easier to understand.

Body:
something like this should suffice.

nestedArrayList = nestedArrayList.stream()
    .filter(e -> !e.isEmpty())
    .collect(Collectors.toCollection(ArrayList::new));

or as Zabuza has suggested, you could use removeIf:

nestedArrayList.removeIf(ArrayList::isEmpty);

IMHO I'd go with the second approach for a couple of reasons but most importantly reading it like "nestedArrayList remove if ArrayList is empty" provides better intent of the code and easier to understand.


问:
Why can't I double-click a button to create an event handler in Silverlight 2.0?
In WPF, ASP.NET, WinForms, I create a button, double-click on it and fill in the event handler.

In Silverlight (with Visual Web Developer 2008), I make a button, double-click it but nothing happens.

Is this not supported when writing Silverlight applications for some reason? Do we have to write these event handlers by hand?

答: The silverlight designer is display only. If you want to move things on screen with your mouse or double click to add events, you need to use expression blend.</p>

OwnerDisplayName: Edward Tanguay

LastEditorDisplayName: Ben Alpert

OwnerDisplayName: Aaron Fischer


问:
Trying to create user types: 'Client' and 'Employee'. Would like all users who register on site to be Clients, who see different page than employee
I'm reading through these docs on Django:
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user

I'm just not sure which route to go. They suggest using a custom user model like so:

```<code>from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass
</code>```

Doing so, what would the procedure be to make two different user types. Should I have something like this:

```<code>class Client(AbstractUser):
        pass

class Employee(AbstractUser):
        pass
</code>```

But then how would new registered users be 'clients' when they sign up? And how would I make it so they see a different part of the site than employees?

I'm just looking for some guidance in how I should approach this.

答:
Are you only addressing a question of permissions, or do 'Client' and 'Employee' need their own specific functionality?

If it is just about permissions, then it would be easier to use the permissions functionality of the auth library.

You can then protect your views with the permissions decorator.

From the docs:

```<code>from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url='/loginpage/')
def my_view(request):
    ...
</code>```

Body:
I'm reading through these docs on Django:
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user

I'm just not sure which route to go. They suggest using a custom user model like so:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

Doing so, what would the procedure be to make two different user types. Should I have something like this:

class Client(AbstractUser):
        pass

class Employee(AbstractUser):
        pass

But then how would new registered users be 'clients' when they sign up? And how would I make it so they see a different part of the site than employees?

I'm just looking for some guidance in how I should approach this.

Body:
Are you only addressing a question of permissions, or do 'Client' and 'Employee' need their own specific functionality?

If it is just about permissions, then it would be easier to use the permissions functionality of the auth library.

You can then protect your views with the permissions decorator.

From the docs:

from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url='/loginpage/')
def my_view(request):
    ...


问:
How to change tab order within one control (div) - html
I have a composite control which consists of two different parts - react-based and d3-based. The resulted tab order is incorrect. I can fix it using tabindex attributes but this collides with tab order of overall page.

Is there a way to fix tab order only under some  element in a way it would not affect overall tab order?

Update (providing example): The below control (outlined in blue) has 4 focusable elements. Right now the tab order is not correct. It follows how elements are defined in DOM. Changing the order of elements is tricky (for instance, d3.brush adds brush elements in opposite order).

Using tab index solves the problem in the control but it breaks the tab order for the whole page.

答:
Using tabindex with positive values is a bad idea as a screenreader will still read the page using the DOM order, and having a different order for keyboard navigation would be very disturbing.

In terms of accessibility you should have an equivalence between : visual order (=CSS order), screenreader reading order (=DOM order), and keyboard order.

In your case, the best solution is to invert the DOM order to match the visual order.

You can also inhibit the links in the tab order (by setting tabindex=-1) and give alternative accessible controls.


问:
Comparing text: what is the best approach
I have a database which stores sequential versions of a text file. What I would like to do is allow the user to call up any two historical files (e.g version 1 And version 4) and compare them for differences:

Spelling changes

New words / new sentences / new paragraphs

Moved paragraphs

Etc

Basically an online GIT but for text files not code.

I figure JavaScript is probably the best approach and I presume that there must be an open source library but I simply cannot find one.

Any assistance appreciated.

答:
If you are running under linux, you could install diff, save both files in temp files, then compare them using the shell_exec command.

For example

```<code>$tmp1 = 'myfile.txt';
$tmp2 = 'myfile2.txt';
$output = shell_exec('diff -y {$tmp1} {$tmp2}');
</code>```

Look at man diff for an option that suits your needs.

Body:
If you are running under linux, you could install diff, save both files in temp files, then compare them using the shell_exec command.

For example

$tmp1 = 'myfile.txt';
$tmp2 = 'myfile2.txt';
$output = shell_exec('diff -y {$tmp1} {$tmp2}');

Look at man diff for an option that suits your needs.


问:
Bash script help, include sub-directories for processing files
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.  </p>

```<code>#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done
</code>```

答: Try to use find command to get the list of all file and directories

Body:
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.

#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done


问:
Escape single quote character for use in an SQLite query
I wrote the database schema (only one table so far), and the INSERT statements for that table in one file. Then I created the database as follows:

```<code>$ sqlite3 newdatabase.db
SQLite version 3.4.0
Enter ".help" for instructions
sqlite> .read ./schema.sql
SQL error near line 16: near "s": syntax error
</code>```

Line 16 of my file looks something like this:

```<code>INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there\'s');
</code>```

The problem is the escape character for a single quote. I also tried double escaping the single quote (using \\\' instead of \'), but that didn't work either. What am I doing wrong?

答:
In C# you can use the following to replace the single quote with a double quote:

```<code> string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");
</code>```

And the output will be:

```<code>"St. Mary''s"
</code>```

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

```<code>private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}
</code>```

OwnerDisplayName: jpm

Body:
I wrote the database schema (only one table so far), and the INSERT statements for that table in one file. Then I created the database as follows:

$ sqlite3 newdatabase.db
SQLite version 3.4.0
Enter ".help" for instructions
sqlite> .read ./schema.sql
SQL error near line 16: near "s": syntax error

Line 16 of my file looks something like this:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there\'s');

The problem is the escape character for a single quote. I also tried double escaping the single quote (using \\\' instead of \'), but that didn't work either. What am I doing wrong?

Body:
In C# you can use the following to replace the single quote with a double quote:

 string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");

And the output will be:

"St. Mary''s"

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}


答:
Lambdas above as posted by Aomine or iterator like this:</p>

```<code>package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

     ArrayList<ArrayList<Integer>> lista = new ArrayList<>(){{
         add(new ArrayList<>(Arrays.asList(1,2,3)));
         add(new ArrayList<>());
     }};

     Iterator<ArrayList<Integer>> iter = lista.iterator();

     while(iter.hasNext()){
         if (iter.next().isEmpty())
             iter.remove();
    }

        System.out.println(lista);

    }

}
</code>```

Title: Remove all empty ArrayLists from an ArrayList with Java

Body:
I want to go through my ArrayList of ArrayLists and remove all the ones that are empty. Is there a fast and efficient way to do this, other then I guess a for loop?

Example Ouput:

[ [alec, joe, ray], [], [eric, jacob], [] ]

Would then look like this:

[ [alec, joe, ray], [eric, jacob] ]

Body:
Lambdas above as posted by Aomine or iterator like this:

package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

     ArrayList<ArrayList<Integer>> lista = new ArrayList<>(){{
         add(new ArrayList<>(Arrays.asList(1,2,3)));
         add(new ArrayList<>());
     }};

     Iterator<ArrayList<Integer>> iter = lista.iterator();

     while(iter.hasNext()){
         if (iter.next().isEmpty())
             iter.remove();
    }

        System.out.println(lista);

    }

}


问:
VBA: Code review
I am new to excel macro, but have basic understanding.

I am trying to find a max value from Sheet1, where I have the code but want to know how I get the same result if I run this code from any other sheets I have on my workbook.

```<code>Sub FindMaxDate()
Set Worksheet = Sheets("Sheet1")
Max_date = Application.WorksheetFunction.Max(Columns("A"))
MsgBox CDate(Max_date)
End Sub
</code>```

For example: I have date filed on Sheet1.Range("A:A") and the max date available there is 01.01.2018 (Cod will give me the same value), but if I am on Sheet2 and run this code it will take value from Sheet2 and show me "12:00:00 AM".

Some one please help me to correct this code so that it will always show the max value from Sheet1 ( 01.01.2018 )

Hope you guys get my queston. Else please let me know.

Thank you

答:
```<code>Sub FindMaxDate()
Set Worksheet = Sheets("Sheet1")
Max_date = Application.WorksheetFunction.Max(Worksheet.Columns("A"))
MsgBox CDate(Max_date)
End Sub
</code>```

Title: VBA: Code review

Body:
I am new to excel macro, but have basic understanding.

I am trying to find a max value from Sheet1, where I have the code but want to know how I get the same result if I run this code from any other sheets I have on my workbook.

Sub FindMaxDate()
Set Worksheet = Sheets("Sheet1")
Max_date = Application.WorksheetFunction.Max(Columns("A"))
MsgBox CDate(Max_date)
End Sub

For example: I have date filed on Sheet1.Range("A:A") and the max date available there is 01.01.2018 (Cod will give me the same value), but if I am on Sheet2 and run this code it will take value from Sheet2 and show me "12:00:00 AM".

Some one please help me to correct this code so that it will always show the max value from Sheet1 ( 01.01.2018 )

Hope you guys get my queston. Else please let me know.

Thank you


问:
mssql query for auto complate
When I question a word, it completes the word or adds new words to it.
Unique first 10 recordings.

```<code>declare @Category table (CategoryName  varchar(50))

insert into @Category (CategoryName) values('phones')
insert into @Category (CategoryName) values('phone blue')
insert into @Category (CategoryName) values('phone pink')
insert into @Category (CategoryName) values('phone big')
insert into @Category (CategoryName) values('phone big bang')
insert into @Category (CategoryName) values('bad phone blue')
insert into @Category (CategoryName) values('bad phone pink')
insert into @Category (CategoryName) values('bad phone but good')
</code>```

I would like the following result when calling as category name "phone"

phone blue

phone pink

phone big

phone but

I would like the following result when calling as category name "phon"

phone

phones

答:
```<code>declare @Category table (CategoryName  varchar(50))

insert into @Category (CategoryName) values('phones')
insert into @Category (CategoryName) values('phone blue')
insert into @Category (CategoryName) values('phone pink')
insert into @Category (CategoryName) values('phone big')
insert into @Category (CategoryName) values('phone big bang')
insert into @Category (CategoryName) values('bad phone blue')
insert into @Category (CategoryName) values('bad phone pink')
insert into @Category (CategoryName) values('bad phone but good')

declare @searchWord varchar(50) = 'phone';
declare @res int;

set @res = (select case when (select count(*) from @Category
                 where substring(CategoryName, 0, CHARINDEX(' ', CategoryName)) = @searchWord) > 0
                 then 1
                 else 0
            end)
if(@res = 1)
begin
    select top 10 CategoryName from @Category where CategoryName like''+@searchWord+'%' and CategoryName like '% %' order by CategoryName
end
else
begin
    select top 10 CategoryName from @Category where CategoryName like''+@searchWord+'%' and CategoryName not like '% %' order by CategoryName
end
</code>```

I hope this helps.

Title: mssql query for auto complate

Body:
When I question a word, it completes the word or adds new words to it.
Unique first 10 recordings.

declare @Category table (CategoryName  varchar(50))

insert into @Category (CategoryName) values('phones')
insert into @Category (CategoryName) values('phone blue')
insert into @Category (CategoryName) values('phone pink')
insert into @Category (CategoryName) values('phone big')
insert into @Category (CategoryName) values('phone big bang')
insert into @Category (CategoryName) values('bad phone blue')
insert into @Category (CategoryName) values('bad phone pink')
insert into @Category (CategoryName) values('bad phone but good')

I would like the following result when calling as category name "phone"

phone blue

phone pink

phone big

phone but

I would like the following result when calling as category name "phon"

phone

phones

Body:
declare @Category table (CategoryName  varchar(50))

insert into @Category (CategoryName) values('phones')
insert into @Category (CategoryName) values('phone blue')
insert into @Category (CategoryName) values('phone pink')
insert into @Category (CategoryName) values('phone big')
insert into @Category (CategoryName) values('phone big bang')
insert into @Category (CategoryName) values('bad phone blue')
insert into @Category (CategoryName) values('bad phone pink')
insert into @Category (CategoryName) values('bad phone but good')

declare @searchWord varchar(50) = 'phone';
declare @res int;

set @res = (select case when (select count(*) from @Category
                 where substring(CategoryName, 0, CHARINDEX(' ', CategoryName)) = @searchWord) > 0
                 then 1
                 else 0
            end)
if(@res = 1)
begin
    select top 10 CategoryName from @Category where CategoryName like''+@searchWord+'%' and CategoryName like '% %' order by CategoryName
end
else
begin
    select top 10 CategoryName from @Category where CategoryName like''+@searchWord+'%' and CategoryName not like '% %' order by CategoryName
end

I hope this helps.


问:
Try-Catch to loop back to while loop Java
I have a project to create a program that picks a number (1-10), then has the user guess. If they are too high it tells them so and same goes for if they guessed too low. Now to mistake-proof it, I have to add try and catch blocks. If you look at the code you will see that I have but when triggered the code processes the catch then finishes. How do I get it to loop back?</p>

```<code>    import java.util.*;
    import java.lang.*;

    class GuessDR {

        public static void main(String[] args){

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;
            Scanner input = new Scanner(System.in);
            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;

             try{

               while (win == false){

                   System.out.println("Guess a number between 1 and "+
                   maxnum +": ");
                   guess = input.nextInt();
                   tries++;
                   if (guess == number){
                       win = true;
                   }

                   else if(guess < number){
                       System.out.println("Number is to low, tray again");

                   }

                   else if(guess > number){
                       System.out.println("Number is to high, try again");

                   }

               }
            }

            catch (InputMismatchException e) {

                System.out.println("Enter numerical guess");

            }
     System.out.println("You win!");
     System.out.println("It took you "+ tries + " tries.");

    }
 }
</code>```

答:
Just move try-catch into the while loop and also provide proper input.nextLine() method inside your catch block to clear invalid input from the buffer:

```<code>   import java.util.*;
   import java.lang.*;

    class GuessDR {

        public static void main(String[] args) {

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;

            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;
            Scanner input = new Scanner(System.in);

            while (win == false) {
                try {

                    System.out.println("Guess a number between 1 and " + maxnum + ": ");
                    guess = input.nextInt();
                    tries++;
                    if (guess == number) {
                        win = true;
                    }

                    else if (guess < number) {
                        System.out.println("Number is to low, tray again");

                    }

                    else if (guess > number) {
                        System.out.println("Number is to high, try again");

                    }

                } catch (InputMismatchException e) {
                    input.nextLine();
                    System.out.println("Enter numerical guess");

                }
            }

            System.out.println("You win!");
            System.out.println("It took you " + tries + " tries.");

        }
    }
</code>```

Body:
I have a project to create a program that picks a number (1-10), then has the user guess. If they are too high it tells them so and same goes for if they guessed too low. Now to mistake-proof it, I have to add try and catch blocks. If you look at the code you will see that I have but when triggered the code processes the catch then finishes. How do I get it to loop back?

    import java.util.*;
    import java.lang.*;

    class GuessDR {

        public static void main(String[] args){

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;
            Scanner input = new Scanner(System.in);
            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;

             try{

               while (win == false){

                   System.out.println("Guess a number between 1 and "+
                   maxnum +": ");
                   guess = input.nextInt();
                   tries++;
                   if (guess == number){
                       win = true;
                   }

                   else if(guess < number){
                       System.out.println("Number is to low, tray again");

                   }

                   else if(guess > number){
                       System.out.println("Number is to high, try again");

                   }

               }
            }

            catch (InputMismatchException e) {

                System.out.println("Enter numerical guess");

            }
     System.out.println("You win!");
     System.out.println("It took you "+ tries + " tries.");

    }
 }

Body:
Just move try-catch into the while loop and also provide proper input.nextLine() method inside your catch block to clear invalid input from the buffer:

   import java.util.*;
   import java.lang.*;

    class GuessDR {

        public static void main(String[] args) {

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;

            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;
            Scanner input = new Scanner(System.in);

            while (win == false) {
                try {

                    System.out.println("Guess a number between 1 and " + maxnum + ": ");
                    guess = input.nextInt();
                    tries++;
                    if (guess == number) {
                        win = true;
                    }

                    else if (guess < number) {
                        System.out.println("Number is to low, tray again");

                    }

                    else if (guess > number) {
                        System.out.println("Number is to high, try again");

                    }

                } catch (InputMismatchException e) {
                    input.nextLine();
                    System.out.println("Enter numerical guess");

                }
            }

            System.out.println("You win!");
            System.out.println("It took you " + tries + " tries.");

        }
    }


问:
Vertically aligning a div and an input
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

```<code><input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>
</code>```

css:

```<code>body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}
</code>```

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!

答:
My dear friend, you just do it  </p>

```<code>input, button {
   vertical-align:middle;
}
</code>```

Title: Vertically aligning a div and an input

Body:
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

<input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>

css:

body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!

Body:
My dear friend, you just do it

input, button {
   vertical-align:middle;
}


问:
How do you get % of records per specific count grouping
I have the following data in a table called users

```<code>   userId   | orgId
    1       | 1
    2       | 1
    3       | 2
    4       | 2
    5       | 2
</code>```

I have the following data in a table called activities

```<code>userId   | activityId | type
1        | 11         | a
1        | 12         | a
1        | 13         | a
1        | 14         | b
1        | 15         | b
1        | 16         | c
1        | 17         | c
1        | 18         | c
2        | 19         | a
2        | 20         | a
2        | 21         | c
2        | 22         | c
</code>```

I need to be able to calculate the % of users within each orgId who:

have only 1 record in the activities' table wheretype` = 'c'

have 5 records in the activities table where type = 'c'

have 10 records in the activities table where type = 'c'

have 50% of their records in the activities table where type = 'c'

have 80% of their records in the activities table where type = 'c'

So the result should be in this (hopefully possible) format:

```<code>orgId|% who have 1| % who have 5| % who have 10| % who have 50%| % who have 80%
1    | 20         | 54          | 12           | 23            | 32
2    | 22         | 44          | 32           | 44            | 2
3    | 28         | 34          | 24           | 11            | 43
4    | 10         | 14          | 27           | 25            | 45
</code>```

Thank you for any help.

答:
You can use "conditional aggregation" to get the count and percentage per user:

```<code>select userId,
  sum(type = 'c') as countC,
  sum(type = 'c') * 100 / count(*) as percentC
from activities
group by userId
</code>```

The result for your sample data would be:

```<code>| userId | countC | percentC |
|--------|--------|----------|
|      1 |      3 |     37.5 |
|      2 |      2 |       50 |
</code>```

This can be used as a subquery joined with the users table. Then you can again use "conditional aggregation" to get the expected result:

```<code>select u.orgId,
  sum(countC = 1) as `only 1`,
  sum(countC >= 5) as `at least 5`,
  sum(countC >= 10) as `at least 10`,
  sum(percentC >= 50) as `at least 50%`,
  sum(percentC >= 80) as `at least 80%`
from (
  select userId,
    sum(type = 'c') as countC,
    sum(type = 'c') * 100 / count(*) as percentC
  from activities
  group by userId
) a
join users u using(userId)
group by u.orgId
</code>```

Your sample data is not the best for that query. However you would get:

```<code>| orgId | only 1 | at least 5 | at least 10 | at least 50% | at least 80% |
|-------|--------|------------|-------------|--------------|--------------|
|     1 |      0 |          0 |           0 |            1 |            0 |
</code>```

Demo: http://sqlfiddle.com/#!9/b30dae/2

Body:
I have the following data in a table called users

   userId   | orgId
    1       | 1
    2       | 1
    3       | 2
    4       | 2
    5       | 2

I have the following data in a table called activities

userId   | activityId | type
1        | 11         | a
1        | 12         | a
1        | 13         | a
1        | 14         | b
1        | 15         | b
1        | 16         | c
1        | 17         | c
1        | 18         | c
2        | 19         | a
2        | 20         | a
2        | 21         | c
2        | 22         | c

I need to be able to calculate the % of users within each orgId who:

have only 1 record in the activities' table wheretype` = 'c'

have 5 records in the activities table where type = 'c'

have 10 records in the activities table where type = 'c'

have 50% of their records in the activities table where type = 'c'

have 80% of their records in the activities table where type = 'c'

So the result should be in this (hopefully possible) format:

orgId|% who have 1| % who have 5| % who have 10| % who have 50%| % who have 80%
1    | 20         | 54          | 12           | 23            | 32
2    | 22         | 44          | 32           | 44            | 2
3    | 28         | 34          | 24           | 11            | 43
4    | 10         | 14          | 27           | 25            | 45

Thank you for any help.

Body:
You can use "conditional aggregation" to get the count and percentage per user:

select userId,
  sum(type = 'c') as countC,
  sum(type = 'c') * 100 / count(*) as percentC
from activities
group by userId

The result for your sample data would be:

| userId | countC | percentC |
|--------|--------|----------|
|      1 |      3 |     37.5 |
|      2 |      2 |       50 |

This can be used as a subquery joined with the users table. Then you can again use "conditional aggregation" to get the expected result:

select u.orgId,
  sum(countC = 1) as `only 1`,
  sum(countC >= 5) as `at least 5`,
  sum(countC >= 10) as `at least 10`,
  sum(percentC >= 50) as `at least 50%`,
  sum(percentC >= 80) as `at least 80%`
from (
  select userId,
    sum(type = 'c') as countC,
    sum(type = 'c') * 100 / count(*) as percentC
  from activities
  group by userId
) a
join users u using(userId)
group by u.orgId

Your sample data is not the best for that query. However you would get:

| orgId | only 1 | at least 5 | at least 10 | at least 50% | at least 80% |
|-------|--------|------------|-------------|--------------|--------------|
|     1 |      0 |          0 |           0 |            1 |            0 |

Demo: http://sqlfiddle.com/#!9/b30dae/2


问:
how to establish the point "." as a thousand separator in the numbers of the Y axis in R?
I'm using the plot function and I would like my numbers to have a thousand separator on the Y axis. For example, in the case of 1000 I would like the 1,000 number to be seen on the axis, or in the case of 10000, for example, on the 10,000 axis .</p>

答:
If you are using base plot() you can turn off the default axes, then just use axis() to draw whatever you like on the axes

```<code>x<-seq(0, 100000, length.out=11)
y<-seq(0, 10000, length.out=11)
plot(x,y, xaxt="n", yaxt="n")

axis(1, axTicks(1), format(axTicks(1), big.mark = "."))
axis(2, axTicks(2), format(axTicks(2), big.mark = "."))
</code>```

Body:
If you are using base plot() you can turn off the default axes, then just use axis() to draw whatever you like on the axes

x<-seq(0, 100000, length.out=11)
y<-seq(0, 10000, length.out=11)
plot(x,y, xaxt="n", yaxt="n")

axis(1, axTicks(1), format(axTicks(1), big.mark = "."))
axis(2, axTicks(2), format(axTicks(2), big.mark = "."))


问:
How does instructions like I/O work in user mode?
I am curious because I am reading this OS book which mentions

"User programs always run in user mode, which permits only a subset of the instructions [...]. Generally, all instructions involving I/O and memory protection are disallowed in user mode.
To obtain services from the OS, a user program must make a system call, which traps into the kernel and invokes the OS."

If I/O is not allowed generally in user mode, but let's say I have a program in C++ or Java which asks for input, or let's say something else like a search bar in any program. Whenever I select the search bar (meaning I will write something) then a TRAP instruction is called to invoke the OS (since the OS runs in kernel) to be able to have access to I/O, that is, the keyboard? I am not sure if I follow correctly or what am I getting wrong.

The I/O is not allowed in user mode, but you use Input for applications in the OS, or even with the OS itself there are keyboard commands. If you can use keyboard commands that means the OS is ready for I/O at any time. Then the original statement about I/O instructions being disallowed in user mode.

I am sorry for my ignorance but I am just a little bit confused with these terms and difference between user and kernel. I know the OS runs in kernel mode, and the applications run in the OS, so in the end the applications do have access to I/O.

答:
Toss your book in the garbage or use it to line a cat box.

Your apparent paradox is that you think you have to be in kernel mode to do I/O but your book says:

"User programs always run in user mode, which permits only a subset of the instructions"

The resolution to your paradox is that your book is spouting nonsense.

Use programs do not always run in user mode. They frequently run in kernel mode. One of the basic functions of an operating system is to provide a set of kernel mode system services that provide controlled access to kernel mode.

In other words, your instincts here are better than your confusing book's text.


问:
how to determine sizeof class with virtual functions?
this is kind of homework question. For the following code,

```<code>#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}
</code>```

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

答:
The size of the object has nothing to do with how many methods that it has, nor with whether those methods are virtual or not. The size of an object is determined solely by its member variables.

I can't tell you exactly why you're getting a size of 8 bytes. Since there are no data members in your class, a C++ compiler could in principle generate a class that occupies no space at all [1]! I'm guessing that the 8 bytes is the minimum required to provide a pointer to the vtbl, plus possibly some padding.

[1] I think. No time to check the spec to find out at the moment whether sizeof can ever return 0.

Body:
this is kind of homework question. For the following code,

#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public:
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.


问:
get the count of columns contains a string in pandas
I have two dataframes df1 and df2.

df1:

```<code>PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12
</code>```

df2:

```<code>PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
</code>```

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

答:
I think u only need this</p>

```<code>df1['count_of_colors'] =df1['PartNumber'].map(df2['PartNumber'].value_counts())
</code>```

Body:
I have two dataframes df1 and df2.

df1:

PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12

df2:

PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

Body:
I think u only need this

df1['count_of_colors'] =df1['PartNumber'].map(df2['PartNumber'].value_counts())


问:
loop over columns and display results
I want to loop over a table in oracle, find the null values in each column, and then update those values,
for now I am trying to just output the number of null values in each column, but i'm getting an error message :

```<code>SET FEEDBACK OFF;
SET SERVEROUTPUT ON;

DECLARE
   N_NULLS       NUMBER;
   BEGIN
   FOR I IN (SELECT COLUMN_NAME
               FROM ALL_TAB_COLUMNS
              WHERE TABLE_NAME = 'my_table')
   LOOP
          SELECT SUM (CASE WHEN I IS NULL THEN 1 ELSE 0 END)
        INTO N_NULLS
        FROM my_table
       WHERE COLUMN_ITEM IS NULL;

      DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);
   END LOOP;
END;
/
</code>```

I get the following errors :

```<code>Error at line 10
ORA-06550: line 9, column 23:
PLS-00382: expression is of wrong type
ORA-06550: line 9, column 8:
PL/SQL: Statement ignored
ORA-06550: line 10, column 29:
PLS-00382: expression is of wrong type
</code>```

答:
```<code>(CASE WHEN I IS NULL THEN 1 ELSE 0 END)
</code>```

should be

```<code>(CASE WHEN I.COLUMN_NAME IS NULL THEN 1 ELSE 0 END)
</code>```

Same issue here:

```<code>DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);
</code>```

Title: loop over columns and display results

Body:
I want to loop over a table in oracle, find the null values in each column, and then update those values,
for now I am trying to just output the number of null values in each column, but i'm getting an error message :

SET FEEDBACK OFF;
SET SERVEROUTPUT ON;

DECLARE
   N_NULLS       NUMBER;
   BEGIN
   FOR I IN (SELECT COLUMN_NAME
               FROM ALL_TAB_COLUMNS
              WHERE TABLE_NAME = 'my_table')
   LOOP
          SELECT SUM (CASE WHEN I IS NULL THEN 1 ELSE 0 END)
        INTO N_NULLS
        FROM my_table
       WHERE COLUMN_ITEM IS NULL;

      DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);
   END LOOP;
END;
/

I get the following errors :

Error at line 10
ORA-06550: line 9, column 23:
PLS-00382: expression is of wrong type
ORA-06550: line 9, column 8:
PL/SQL: Statement ignored
ORA-06550: line 10, column 29:
PLS-00382: expression is of wrong type

Body:
(CASE WHEN I IS NULL THEN 1 ELSE 0 END)

should be

(CASE WHEN I.COLUMN_NAME IS NULL THEN 1 ELSE 0 END)

Same issue here:

DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);


问:
"wait_fences: failed to receive reply: 10004003"?
I get this cryptic error the first time (and only the first time) my view is loaded due to the following line of code:

```<code>- (void)viewWillAppear:(BOOL)animated
{
    [textField becomeFirstResponder];
}
</code>```

There is a noticeable (~3 – 4 second, even on the simulator) delay due to this that makes my app feel unresponsive. Does anyone know how to fix this? I can't find any documentation on it on Apple's site, or any solutions here or on Google.

Strangely, the opposite situation happens if I put the line in -viewDidAppear: instead of -viewWillAppear:; that is, instead of printing the error only the first time the keyboard is shown and never again, the error is not printed the first time but every time after. This is causing a major headache for me.

答: I also get the message wait_fences: failed to receive reply: 10004003 and my viewWill... and viewDid... methods do nothing but send messages to super. In my case it happens when I have a UIAlertView showing in my GameViewController and the user instead presses the iPhone round device button and then returns to the app. This looks out of my hands.

Body:
I get this cryptic error the first time (and only the first time) my view is loaded due to the following line of code:

- (void)viewWillAppear:(BOOL)animated
{
    [textField becomeFirstResponder];
}

There is a noticeable (~3 – 4 second, even on the simulator) delay due to this that makes my app feel unresponsive. Does anyone know how to fix this? I can't find any documentation on it on Apple's site, or any solutions here or on Google.

Strangely, the opposite situation happens if I put the line in -viewDidAppear: instead of -viewWillAppear:; that is, instead of printing the error only the first time the keyboard is shown and never again, the error is not printed the first time but every time after. This is causing a major headache for me.


问:
Scope of global array javascript
I am trying to load data from a csv and store it in an array of objects.  I know global variables are frowned upon but I can't think of a better way to store the data and access it from multiple functions.

Here is my code:

```<code>var mydata = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var head = data.split("\n");
        for(var i = 1; i < head.length; i++){
            line = head[i].split(",");
            var obj = {
                index:i,
                img:line[0],
                caption:line[1],
                desc:line[2]
            };
            mydata.push(obj);
        }
        console.log(mydata); //1
    });
    console.log(mydata); //2
    //I then want to select various elements on my page and set some attributes to
    //an object in my data, but I can't since everything is undefined
});
</code>```

At the first spot it logs my data correctly, but at second spot it logs an empty array.  I read this article on global variables in JavaScript so I'm not sure what is going wrong.

答:
At 2 the data will be same as what you initialized. At 1 the data will be the same as what you populated.

2 gets printed first if you have observed closely. This is because $.get is an asynchronous call and gets executed in the background. The callback you are providing to $.get will run after the GET request is either successfully completed or errored out.

Title: Scope of global array javascript

Body:
I am trying to load data from a csv and store it in an array of objects.  I know global variables are frowned upon but I can't think of a better way to store the data and access it from multiple functions.

Here is my code:

var mydata = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var head = data.split("\n");
        for(var i = 1; i < head.length; i++){
            line = head[i].split(",");
            var obj = {
                index:i,
                img:line[0],
                caption:line[1],
                desc:line[2]
            };
            mydata.push(obj);
        }
        console.log(mydata); //1
    });
    console.log(mydata); //2
    //I then want to select various elements on my page and set some attributes to
    //an object in my data, but I can't since everything is undefined
});

At the first spot it logs my data correctly, but at second spot it logs an empty array.  I read this article on global variables in JavaScript so I'm not sure what is going wrong.


问:
How to get value of textbox on page load, if it is null?

Want to check first that, Is text box contains nothing on page load ?

Then assign some value to it.

```<code>if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
</code>```

But getting error
"JavaScript runtime error: Unable to set property 'value' of undefined or null reference"
How to do this?

答:
Please try the below code, you need to set the value to the null first in the line

```<code>Name: <input type="text" id="myText" value=''>
</code>```

Here is the demo :

function func() {
  if (document.getElementById("myText").value == '') {
    document.getElementById("myText").value = "Some text here";
  } else {
    alert("not null");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Name: <input type="text" id="myText" value="">

<p>Click the button to change the value of the text field.</p>
<input type="button" id="button" value="Click Me" onClick="func();" /></code>```

Body:
Want to check first that, Is text box contains nothing on page load ?

Then assign some value to it.

if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}

But getting error
"JavaScript runtime error: Unable to set property 'value' of undefined or null reference"
How to do this?

Body:
Please try the below code, you need to set the value to the null first in the line

Name: <input type="text" id="myText" value=''>

Here is the demo :

function func() {
  if (document.getElementById("myText").value == '') {
    document.getElementById("myText").value = "Some text here";
  } else {
    alert("not null");
  }
}

Name: <input type="text" id="myText" value="">

<p>Click the button to change the value of the text field.</p>
<input type="button" id="button" value="Click Me" onClick="func();" />