问:
Factory with Composite or Abstract Factory
I have following class hierarchy:

public interface RateSheetProductExtractor
{
  List<ProductData> extract(SGQuotingData quotingData);
}

@Service
@Scope("requestjob")
public class ProductExtractorFactory
{
  @Autowired
  private OptionalRatingProductExtractorFactory optionalRatingProductExtractorFactory;
  @Autowired
  private QuotePlanProductExtractorFactory quotePlanProductExtractorFactory;
  @Autowired
  private AlternateProductExtractorFactory alternateProductExtractorFactory;

  public RateSheetProductExtractor getProductExtractor(
    TablePlanType tablePlanType,
    TableRatingType ratingType)
  {
    switch (tablePlanType)
    {
      case QUOTED:
        return quotePlanProductExtractorFactory.getInstance(ratingType);
      case OPTIONAL:
        return optionalRatingProductExtractorFactory.getInstance(ratingType);
      case ALTERNATE:
        return alternateProductExtractorFactory.getInstance(ratingType);
      default:
        throw new IllegalArgumentException(tablePlanType + " is unsupported yet.");
    }
  }
}

@Service
@Scope("requestjob")
public class OptionalRatingProductExtractorFactory
{
  @Autowired
  private AcaProductExtractor acaProductExtractor;
  @Autowired
  private AgeRatedAsCompositeProductExtractor ageRatedAsCompositeProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedAsCompositeProductExtractor;
      case COMPOSITE:
        return acaProductExtractor;
      default:
        throw new IllegalArgumentException(
          "Product extractor isn't defined for optional plan type and rating type " + ratingType);

    }
  }
}

@Service
@Scope("requestjob")
public class QuotePlanProductExtractorFactory
{
  @Autowired
  private GfProductExtractor gfExtractor;
  @Autowired
  private AgeRatedProductExtractor ageRatedProductExtractor;
  @Autowired
  private MedicalProductExtractor medicalProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedProductExtractor;
      case COMPOSITE_AGE:
        return gfExtractor;
      case COMPOSITE:
        return medicalProductExtractor;
      default:
        throw new IllegalArgumentException(
          ratingType + " is unsupported for QuotePlan product extractor factory.");
    }
  }
}

@Service
@Scope("requestjob")
public class AlternateProductExtractorFactory
{
  @Autowired
  private AlternateAgeRatedProductExtractor ageRatedProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    if (ratingType == AGE)
    {
      return ageRatedProductExtractor;
    }
    throw new IllegalArgumentException(
      ratingType + " is unsupported for QuotePlan product extractor factory.");
  }
}```

would it be correct to call ProductExtractorFactory as AbstractProductExtractorFactory(based on the appropriate pattern)? or it's more like a simple factory of factories?

Sorry for huge listing...:)

答:
I dont think so.

1) ProductExtractorFactory is a concrete class and in Java and even in AbstractFactory pattern the class that starts with Abstract is/should be an abstract class.

2) In Abstract factory you should have a concrete subtype of RateSheetProductExtractor for each factory but in your code example I dont see them.

3) You example is more like a Factory along with Composite pattern.

Refactoring to use composite:

Define common factory interface:

```<code>public interface RateSheetProductExtractorFactory{

    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType);
}
</code>```

Define composite class:

```<code>public class CompositeRateSheetProductExtractorFactory implements RateSheetProductExtractorFactory{
    private Map<String, RateSheetProductExtractorFactory> factoryMap = null;

    public void setFactoryMap(Map<String, RateSheetProductExtractorFactory> factoryMap){
        this.factoryMap = factoryMap;
    }

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        RateSheetProductExtractorFactory factory = factoryMap.get( tablePlanType + "-" + ratingType );

        if (factory == null) throw new IllegalArgumentException( tablePlanType + "-" + ratingType + " is unsupported yet.");

        return factory.getProductExtractor(tablePlanType, ratingType);
    }
}
</code>```

Implements each extractor and their individual factories:

```<code>public class AcaProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new AcaProductExtractor();
    }
}

public class AcaProductExtractor implements RateSheetProductExtractor{

    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}

public class AgeRatedAsCompositeProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new AgeRatedAsCompositeProductExtractor();
    }
}

public class AgeRatedAsCompositeProductExtractor implements RateSheetProductExtractor{

    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}

public class MedicalProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new MedicalProductExtractor();
    }
}

public class MedicalProductExtractor implements RateSheetProductExtractor{
    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}
</code>```

Spring XML:

```<code><bean id="ageRatedAsCompositeProductExtractorFactory" class="AgeRatedAsCompositeProductExtractorFactory"/>
<bean id="medicalProductExtractorFactory" class="MedicalProductExtractorFactory"/>
<bean id="acaProductExtractorFactory" class="AcaProductExtractorFactory"/>

<bean id="extractorFactory" class="CompositeRateSheetProductExtractorFactory">
    <property name="factoryMap">
        <map>
            <entry key="QUOTED-AGE" value-ref="ageRatedAsCompositeProductExtractorFactory" />
            <entry key="QUOTED-COMPOSITE" value-ref="medicalProductExtractorFactory" />
            <entry key="ALTERNATE-AGE" value-ref="ageRatedAsCompositeProductExtractorFactory" />
            <entry key="OPTIONAL-COMPOSITE" value-ref="acaProductExtractorFactory" />
        </map>
    </property>
</bean>
</code>```

Body:
I have following class hierarchy:

public interface RateSheetProductExtractor
{
  List<ProductData> extract(SGQuotingData quotingData);
}

@Service
@Scope("requestjob")
public class ProductExtractorFactory
{
  @Autowired
  private OptionalRatingProductExtractorFactory optionalRatingProductExtractorFactory;
  @Autowired
  private QuotePlanProductExtractorFactory quotePlanProductExtractorFactory;
  @Autowired
  private AlternateProductExtractorFactory alternateProductExtractorFactory;

  public RateSheetProductExtractor getProductExtractor(
    TablePlanType tablePlanType,
    TableRatingType ratingType)
  {
    switch (tablePlanType)
    {
      case QUOTED:
        return quotePlanProductExtractorFactory.getInstance(ratingType);
      case OPTIONAL:
        return optionalRatingProductExtractorFactory.getInstance(ratingType);
      case ALTERNATE:
        return alternateProductExtractorFactory.getInstance(ratingType);
      default:
        throw new IllegalArgumentException(tablePlanType + " is unsupported yet.");
    }
  }
}

@Service
@Scope("requestjob")
public class OptionalRatingProductExtractorFactory
{
  @Autowired
  private AcaProductExtractor acaProductExtractor;
  @Autowired
  private AgeRatedAsCompositeProductExtractor ageRatedAsCompositeProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedAsCompositeProductExtractor;
      case COMPOSITE:
        return acaProductExtractor;
      default:
        throw new IllegalArgumentException(
          "Product extractor isn't defined for optional plan type and rating type " + ratingType);

    }
  }
}

@Service
@Scope("requestjob")
public class QuotePlanProductExtractorFactory
{
  @Autowired
  private GfProductExtractor gfExtractor;
  @Autowired
  private AgeRatedProductExtractor ageRatedProductExtractor;
  @Autowired
  private MedicalProductExtractor medicalProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedProductExtractor;
      case COMPOSITE_AGE:
        return gfExtractor;
      case COMPOSITE:
        return medicalProductExtractor;
      default:
        throw new IllegalArgumentException(
          ratingType + " is unsupported for QuotePlan product extractor factory.");
    }
  }
}

@Service
@Scope("requestjob")
public class AlternateProductExtractorFactory
{
  @Autowired
  private AlternateAgeRatedProductExtractor ageRatedProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    if (ratingType == AGE)
    {
      return ageRatedProductExtractor;
    }
    throw new IllegalArgumentException(
      ratingType + " is unsupported for QuotePlan product extractor factory.");
  }
}

would it be correct to call ProductExtractorFactory as AbstractProductExtractorFactory(based on the appropriate pattern)? or it's more like a simple factory of factories?

Sorry for huge listing...:)

Body:
I dont think so.

1) ProductExtractorFactory is a concrete class and in Java and even in AbstractFactory pattern the class that starts with Abstract is/should be an abstract class.

2) In Abstract factory you should have a concrete subtype of RateSheetProductExtractor for each factory but in your code example I dont see them.

3) You example is more like a Factory along with Composite pattern.

Refactoring to use composite:

Define common factory interface:

public interface RateSheetProductExtractorFactory{

    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType);
}

Define composite class:

public class CompositeRateSheetProductExtractorFactory implements RateSheetProductExtractorFactory{
    private Map<String, RateSheetProductExtractorFactory> factoryMap = null;

    public void setFactoryMap(Map<String, RateSheetProductExtractorFactory> factoryMap){
        this.factoryMap = factoryMap;
    }

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        RateSheetProductExtractorFactory factory = factoryMap.get( tablePlanType + "-" + ratingType );

        if (factory == null) throw new IllegalArgumentException( tablePlanType + "-" + ratingType + " is unsupported yet.");

        return factory.getProductExtractor(tablePlanType, ratingType);
    }
}

Implements each extractor and their individual factories:

public class AcaProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new AcaProductExtractor();
    }
}

public class AcaProductExtractor implements RateSheetProductExtractor{

    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}

public class AgeRatedAsCompositeProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new AgeRatedAsCompositeProductExtractor();
    }
}

public class AgeRatedAsCompositeProductExtractor implements RateSheetProductExtractor{

    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}

public class MedicalProductExtractorFactory implements RateSheetProductExtractorFactory{

    @Override
    public RateSheetProductExtractor getProductExtractor(TablePlanType tablePlanType, TableRatingType ratingType){
        return new MedicalProductExtractor();
    }
}

public class MedicalProductExtractor implements RateSheetProductExtractor{
    @Override
    public List<ProductData> extract(SGQuotingData quotingData) {
        return null;
    }
}

Spring XML:

<bean id="ageRatedAsCompositeProductExtractorFactory" class="AgeRatedAsCompositeProductExtractorFactory"/>
<bean id="medicalProductExtractorFactory" class="MedicalProductExtractorFactory"/>
<bean id="acaProductExtractorFactory" class="AcaProductExtractorFactory"/>

<bean id="extractorFactory" class="CompositeRateSheetProductExtractorFactory">
    <property name="factoryMap">
        <map>
            <entry key="QUOTED-AGE" value-ref="ageRatedAsCompositeProductExtractorFactory" />
            <entry key="QUOTED-COMPOSITE" value-ref="medicalProductExtractorFactory" />
            <entry key="ALTERNATE-AGE" value-ref="ageRatedAsCompositeProductExtractorFactory" />
            <entry key="OPTIONAL-COMPOSITE" value-ref="acaProductExtractorFactory" />
        </map>
    </property>
</bean>


来源: stackexchange

问:
jquery form submission button not working on mobile / touchscreens
Form submit button not working on mobile / touchscreen devices, it works on laptops but on mobile devices nothing happens, code below:</p>

```<code>  $('[data-behavior="publish-button"]').on('click', function() {
    $('.editor-form').submit();
  });

  $('.publish-dropdown').on('click', function(e) {
  e.stopPropagation();
  });
},
</code>```

答:
You can try the following code:-</p>

```<code>$('[data-behavior="publish-button"]').on('click touchstart', function() {
  $('.editor-form').submit();
});

$('.publish-dropdown').on('click touchstart', function(e) {
  e.stopPropagation();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Form submit button not working on mobile / touchscreen devices, it works on laptops but on mobile devices nothing happens, code below:

  $('[data-behavior="publish-button"]').on('click', function() {
    $('.editor-form').submit();
  });

  $('.publish-dropdown').on('click', function(e) {
  e.stopPropagation();
  });
},

Body:
You can try the following code:-

$('[data-behavior="publish-button"]').on('click touchstart', function() {
  $('.editor-form').submit();
});

$('.publish-dropdown').on('click touchstart', function(e) {
  e.stopPropagation();
});


问:
Why the docker container memory usage doesn't decrease?
I'm running a Java REST app with Apache JavaSpark in this container, but I noticed that each request is adding the memory usage and not decreasing after the request is done. My first guess was that I had forgotten to close some stream/buffer (this app deal with a lot of file manipulation), but I reviewed all the code and looks like everything is being closed.

Here is my Dockerfile:

```<code>FROM maven:3.5-jdk-8-alpine

WORKDIR /code

ADD pom.xml /code/pom.xml

RUN ["mvn", "dependency:resolve"]

ADD src /code/src

RUN ["mvn", "package"]

EXPOSE 1337

CMD exec java -jar "target/app.jar"
</code>```

Here is the docker stats:

```<code>CONTAINER           CPU %               MEM USAGE / LIMIT       MEM %               NET I/O             BLOCK I/O           PIDS
2db8b2f5fd72        0.16%               66.36 MiB / 1.952 GiB   3.32%               12.9 kB / 106 kB    0 B / 0 B           23
</code>```

答:
Java usually allocates memory that has previously reserved, it only frees it when you restart the process. You can see this post that gives the full explanation.

java.exe process uses more memory and does not free it up

Body:
I'm running a Java REST app with Apache JavaSpark in this container, but I noticed that each request is adding the memory usage and not decreasing after the request is done. My first guess was that I had forgotten to close some stream/buffer (this app deal with a lot of file manipulation), but I reviewed all the code and looks like everything is being closed.

Here is my Dockerfile:

FROM maven:3.5-jdk-8-alpine

WORKDIR /code

ADD pom.xml /code/pom.xml

RUN ["mvn", "dependency:resolve"]

ADD src /code/src

RUN ["mvn", "package"]

EXPOSE 1337

CMD exec java -jar "target/app.jar"

Here is the docker stats:

CONTAINER           CPU %               MEM USAGE / LIMIT       MEM %               NET I/O             BLOCK I/O           PIDS
2db8b2f5fd72        0.16%               66.36 MiB / 1.952 GiB   3.32%               12.9 kB / 106 kB    0 B / 0 B           23


问:
package.json does not update dependencies
I recently tried to run my friend's project on my machine using the angular-cli. The dependencies in the package.json were old on his machine so I tried to update them using the following commands:

```<code>npm i -g npm-check-updates
npm-check-updates -u
npm install
</code>```

The commang ng serve did render a few modules but I get these errors.

What should I do?

答:
Install and save the angular animations to the package.json file.</p>

```<code>npm install @angular/animations@latest --save
</code>```

Body:
I recently tried to run my friend's project on my machine using the angular-cli. The dependencies in the package.json were old on his machine so I tried to update them using the following commands:

npm i -g npm-check-updates
npm-check-updates -u
npm install

The commang ng serve did render a few modules but I get these errors.

What should I do?

Body:
Install and save the angular animations to the package.json file.

npm install @angular/animations@latest --save


问:
Word js: how to get the Range object from start and end index
Basically what I want is that, I have start and end index now I want to get the Range object from this start and end index.

OR how do I get the start and end index from the existing range object.

```<code>Word.run(function (context) {
    var range = context.document.getSelection();
    range.select();

    return context.sync().then(function () {
       console.log('Selected the range.');
    });
})
.catch(function (error) {

});
</code>```

Please help me how I can solve this.

Thanks in advance.

答:
The office.js Word.Range object doesn't have numeric start and end points like the VSTO Word.Range object. In office.js, to get the range of a particular word in text, you probably need to do one of the following, depending on exactly what your scenario is.

Use the Range.getRange(rangeLocation) method.

Get the range of the parent paragraph. Then use the Range.getTextRanges(...) method to get all the word ranges in the paragraph and then pick out the range you need from the collection that is returned.

Use Range.search or Paragraph.search to search for the word.

See the reference help for Word.Range.

Body:
Basically what I want is that, I have start and end index now I want to get the Range object from this start and end index.

OR how do I get the start and end index from the existing range object.

Word.run(function (context) {
    var range = context.document.getSelection();
    range.select();

    return context.sync().then(function () {
       console.log('Selected the range.');
    });
})
.catch(function (error) {

});

Please help me how I can solve this.

Thanks in advance.


问:
Async method await keyword doesn't suspend to calling method
I have following line of code, to understand async-await and suspension till awaited task complete.

```<code>public async Task<string> WaitAsynchronouslyAsync()
    {
        var results = await WaitAsync();
        Console.WriteLine($@"I am not waiting");
        return results;
    }

    public async Task<string> WaitAsync()
    {
        await Task.Delay(10000).ConfigureAwait(false);
        return "Async programming suspension point demo.";
    }
</code>```

The await operator suspends execution until the work of the WaitAsync() (Delay 10 seconds) method is complete.

In the meantime, I was expecting that Console.WriteLine($@"I am not waiting"); should write text to output window until awaited task completes, as control is returned to the caller of WaitAsync(). When the task finishes execution, the await expression evaluates string ("Async programming suspension point demo.").

Am I confused here with suspension pointer vs debug pointer?

答:
The await operator suspends execution until the work of the WaitAsync()  method is complete.

Correct.

I was expecting that Console.WriteLine($@"I am not waiting"); should write text to output window until awaited task completes, as control is returned to the caller of WaitAsync().

Why? You just said the await operator suspends execution until the work is complete.  The work will not be complete for another ten seconds; the work is to wait for ten seconds.  The work of WaitAsync is not complete until it executes the return, and that is in the future.

The right thing to do here is for WaitAsynchronouslyAsync to allow its caller an opportunity to run in this scenario.

You have correctly stated the meaning of await, but you seem to not be fully internalizing the consequences. An await checks its operand to see if the task is complete. If it is, then the result of the task is fetched and the method continues. If it is not, then the remainder of the method is signed up as the continuation of that task, and control is yielded so that more work can be done elsewhere. In the future, when the task completes, the remainder of the method is scheduled to execute.

Body:
I have following line of code, to understand async-await and suspension till awaited task complete.

public async Task<string> WaitAsynchronouslyAsync()
    {
        var results = await WaitAsync();
        Console.WriteLine($@"I am not waiting");
        return results;
    }

    public async Task<string> WaitAsync()
    {
        await Task.Delay(10000).ConfigureAwait(false);
        return "Async programming suspension point demo.";
    }

The await operator suspends execution until the work of the WaitAsync() (Delay 10 seconds) method is complete.

In the meantime, I was expecting that Console.WriteLine($@"I am not waiting"); should write text to output window until awaited task completes, as control is returned to the caller of WaitAsync(). When the task finishes execution, the await expression evaluates string ("Async programming suspension point demo.").

Am I confused here with suspension pointer vs debug pointer?


问:
How to give title to NSPersistentDocument window
I have subclassed NSPersistentDocument. I have renamed the window too. But when I run the application I get the title of the application window as "Untitled". There is no -setTitle: method which I can use to change the title. Any ideas how can I go about doing this?

答: You don't change the title, your users do by saving documents.</p>

OwnerDisplayName: shrads

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Chris Hanson


问:
Python Mock Unittest Asserting Mysql Resultsets
I am having a really hard time wrapping my head around using Mock to do non-trivial unit tests in Python. I do not want to use the production databases for my test suits and want to create a testing-only database.

Let's say I want to create a mock database with these 3 tables containing this data:

```<code>FRUIT
id      Name
1       Apple
2       Pear
3       Orange

 COLOR
 id     Name
 1      Red
 2      Yellow
 3      Orange

 FRUIT_COLOR
 id     fruit_id    color_id
 1      1            1
 2      1            2
 3      2            2
 4      3            3
</code>```

Now let's say I have the following function:

```<code>def assess_fruit(self):
    query = """
        SELECT
        f.name AS FRUIT,
        c.name AS COLOR
        FROM fruit_color AS fc
        JOIN fruit AS f ON f.id = fc.fruit_id
        JOIN color AS c ON c.id = fc.color_id
        WHERE color.name = 'Red';
     """
    cursor.execute(self._query)
    results = cursor.fetchall()
    return results
</code>```

How do I got about using Mock to make this database and test that the results should be something like this list of tuples?

```<code> [(Apple, Red), (Apple, Yellow)]
</code>```

Thank you in advance.

答:
Python unit test TestCase class has 2 methods setUp and tearDown which are called when your test cases starts and ends. You can add code to CREATE the tables and INSERT data into the tables in these 2 methods. See example below:

```<code>from unittest import TestCase

class TestMyData(TestCase):

    def setUp(self):
        query = """
        CREATE TABLE FRUIT (
            id INT,
            Name VARCHAR(255)
        );
        INSERT INTO FRUIT (id, Name)
        VALUES (1, 'Apple'),
               (2, 'Pear'),
               (3, 'Orange');
        """
        cursor.execute(query)

        # Add CREATE & INSERT table statements for COLOR and FRUIT_COLOR tables

    def assess_fruit(self):
        query = """
            SELECT
            f.name AS FRUIT,
            c.name AS COLOR
            FROM fruit_color AS fc
            JOIN fruit AS f ON f.id = fc.fruit_id
            JOIN color AS c ON c.id = fc.color_id
            WHERE color.name = 'Red';
         """
        cursor.execute(query)
        results = cursor.fetchall()
        return results

    def tearDown(self):
        query = """
        DROP TABLE FRUIT;
        DROP TABLE COLOR;
        DROP TABLE FRUIT_COLOR;
        """
        cursor.execute(query)
</code>```

If you would like to learn how to actually mock your calls to the database then you can take a look at this blog post I wrote not too long ago.

Body:
I am having a really hard time wrapping my head around using Mock to do non-trivial unit tests in Python. I do not want to use the production databases for my test suits and want to create a testing-only database.

Let's say I want to create a mock database with these 3 tables containing this data:

FRUIT
id      Name
1       Apple
2       Pear
3       Orange

 COLOR
 id     Name
 1      Red
 2      Yellow
 3      Orange

 FRUIT_COLOR
 id     fruit_id    color_id
 1      1            1
 2      1            2
 3      2            2
 4      3            3

Now let's say I have the following function:

def assess_fruit(self):
    query = """
        SELECT
        f.name AS FRUIT,
        c.name AS COLOR
        FROM fruit_color AS fc
        JOIN fruit AS f ON f.id = fc.fruit_id
        JOIN color AS c ON c.id = fc.color_id
        WHERE color.name = 'Red';
     """
    cursor.execute(self._query)
    results = cursor.fetchall()
    return results

How do I got about using Mock to make this database and test that the results should be something like this list of tuples?

 [(Apple, Red), (Apple, Yellow)]

Thank you in advance.

Body:
Python unit test TestCase class has 2 methods setUp and tearDown which are called when your test cases starts and ends. You can add code to CREATE the tables and INSERT data into the tables in these 2 methods. See example below:

from unittest import TestCase

class TestMyData(TestCase):

    def setUp(self):
        query = """
        CREATE TABLE FRUIT (
            id INT,
            Name VARCHAR(255)
        );
        INSERT INTO FRUIT (id, Name)
        VALUES (1, 'Apple'),
               (2, 'Pear'),
               (3, 'Orange');
        """
        cursor.execute(query)

        # Add CREATE & INSERT table statements for COLOR and FRUIT_COLOR tables

    def assess_fruit(self):
        query = """
            SELECT
            f.name AS FRUIT,
            c.name AS COLOR
            FROM fruit_color AS fc
            JOIN fruit AS f ON f.id = fc.fruit_id
            JOIN color AS c ON c.id = fc.color_id
            WHERE color.name = 'Red';
         """
        cursor.execute(query)
        results = cursor.fetchall()
        return results

    def tearDown(self):
        query = """
        DROP TABLE FRUIT;
        DROP TABLE COLOR;
        DROP TABLE FRUIT_COLOR;
        """
        cursor.execute(query)

If you would like to learn how to actually mock your calls to the database then you can take a look at this blog post I wrote not too long ago.


问:
Unable to install SciPy using pip in VIsual Studio 2015 ( Community Edition )
I am using Windows 10 (64-bit) ,python 3.6 with the latest pip version and the latest version on NumPy as well (I installed it using the command pip install numpy). When I tried to install SciPy pip gave me this error :

```<code>Collecting scipy
  Using cached scipy-0.19.0.zip
Installing collected packages: scipy
  Running setup.py install for scipy: started
    Running setup.py install for scipy: finished with status 'error'
    Complete output from command "C:\Program Files (x86)\Python36-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Tanmay\\AppData\\Local\\Temp\\pip-build-_79sv8pm\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Tanmay\AppData\Local\Temp\pip-djlh9ivy-record\install-record.txt --single-version-externally-managed --compile:

    Note: if you need reliable uninstall behavior, then install
    with pip instead of using `setup.py install`:

      - `pip install .`       (from a git repo or downloaded source
                               release)
      - `pip install scipy`   (last SciPy release on PyPI)

    lapack_opt_info:
    lapack_mkl_info:
      libraries mkl_rt not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    openblas_lapack_info:
      libraries openblas not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-builder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Atlas (http://math-atlas.sourceforge.net/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [atlas]) or by setting
        the ATLAS environment variable.
      self.calc_info()
    lapack_info:
      libraries lapack not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      self.calc_info()
    lapack_src_info:
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      self.calc_info()
      NOT AVAILABLE

    Running from scipy source directory.
    non-existing path in 'scipy\\integrate': 'quadpack.h'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 416, in <module>
        setup_package()
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 412, in setup_package
        setup(**metadata)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
        config = configuration()
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 336, in configuration
        config.add_subpackage('scipy')
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
        caller_level = 2)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
        caller_level = caller_level + 1)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\setup.py", line 15, in configuration
        config.add_subpackage('linalg')
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
        caller_level = 2)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
        caller_level = caller_level + 1)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\linalg\setup.py", line 20, in configuration
        raise NotFoundError('no lapack/blas resources found')
    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
Command ""C:\Program Files (x86)\Python36-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Tanmay\\AppData\\Local\\Temp\\pip-build-_79sv8pm\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Tanmay\AppData\Local\Temp\pip-djlh9ivy-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\
----- Failed to install 'scipy' -----

 - enter code here
</code>```

How to i resolve this ?

答: This is a duplicate of many questions. The short answer is: on Windows, use wheels built by Christoph Gohlke, http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy, or switch over to Anaconda.

Body:
I am using Windows 10 (64-bit) ,python 3.6 with the latest pip version and the latest version on NumPy as well (I installed it using the command pip install numpy). When I tried to install SciPy pip gave me this error :

Collecting scipy
  Using cached scipy-0.19.0.zip
Installing collected packages: scipy
  Running setup.py install for scipy: started
    Running setup.py install for scipy: finished with status 'error'
    Complete output from command "C:\Program Files (x86)\Python36-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Tanmay\\AppData\\Local\\Temp\\pip-build-_79sv8pm\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Tanmay\AppData\Local\Temp\pip-djlh9ivy-record\install-record.txt --single-version-externally-managed --compile:

    Note: if you need reliable uninstall behavior, then install
    with pip instead of using `setup.py install`:

      - `pip install .`       (from a git repo or downloaded source
                               release)
      - `pip install scipy`   (last SciPy release on PyPI)

    lapack_opt_info:
    lapack_mkl_info:
      libraries mkl_rt not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    openblas_lapack_info:
      libraries openblas not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-builder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Atlas (http://math-atlas.sourceforge.net/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [atlas]) or by setting
        the ATLAS environment variable.
      self.calc_info()
    lapack_info:
      libraries lapack not found in ['C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\', 'C:\\Program Files (x86)\\Python36-32\\libs']
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      self.calc_info()
    lapack_src_info:
      NOT AVAILABLE

    C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      self.calc_info()
      NOT AVAILABLE

    Running from scipy source directory.
    non-existing path in 'scipy\\integrate': 'quadpack.h'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 416, in <module>
        setup_package()
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 412, in setup_package
        setup(**metadata)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
        config = configuration()
      File "C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\setup.py", line 336, in configuration
        config.add_subpackage('scipy')
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
        caller_level = 2)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
        caller_level = caller_level + 1)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\setup.py", line 15, in configuration
        config.add_subpackage('linalg')
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
        caller_level = 2)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
        caller_level = caller_level + 1)
      File "C:\Program Files (x86)\Python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\linalg\setup.py", line 20, in configuration
        raise NotFoundError('no lapack/blas resources found')
    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
Command ""C:\Program Files (x86)\Python36-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Tanmay\\AppData\\Local\\Temp\\pip-build-_79sv8pm\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Tanmay\AppData\Local\Temp\pip-djlh9ivy-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Tanmay\AppData\Local\Temp\pip-build-_79sv8pm\scipy\
----- Failed to install 'scipy' -----

 - enter code here

How to i resolve this ?


问:
Can reverse proxy in Service Fabric be used with multiple windows containers?
I'm evaluating using SF or docker swarm for container orchestration and I can see service fabric has an edge by being able to use reverse proxy implementation which runs on all nodes in cluster. Problem is that I can see that based on cluster manifest only one port can be used as reverse proxy port and hence I'm not fully understanding how this can be utilized if you have multiple windows containers running with each of those running on their own port. I need to use port:port mapping only (with no HTTP rewrite), so ultimately wanted one to one reverse port mapping to each individual windows container running.
Is it possible to accomplish by using service fabric?

To be clear I have www.app1.com and www.app2.com hosted in 2 different containers, they don't need to talk to each other. I deploy those to service fabric, how do I use reverse proxy with single published external port to reach those containers externally?

答:
At this point in time (version 5.6 of Service Fabric), Reverse Proxy will do the service resolution using the Service Fabric naming service and provide the URI to get to your service. The URL that reverse proxy will find your service on is specific to Service Fabric - e.g. http://clusterFQDN/appName/serviceName:port.

What you can use the DNS Service to get you a container IP (the IP of a host node in the cluster, running your container). However, you can only find the port by doing a DNS SRV record lookup.

Current best options for exposing containers in a Service Fabric cluster are:

If you have a fixed host port for your container, the Azure load balancer will be able to monitor where the container lives, and forward requests to only those nodes. You can add additional public IPs to your Load Balancer and use one per container. Cannot be used with dynamic host ports in the cluster.

Azure API Management can resolve Service Fabric services by integrating with the Service Fabric Naming Service.

Create your own HTTP Gateway as a Reliable Service: https://github.com/weidazhao/Hosting or https://github.com/c3-ls/ServiceFabric-Http

Running Nginx as a service in the cluster: Based on this prototype you can run and configure Nginx in Service Fabric: https://github.com/knom/ServiceFabric-Nginx


问:
How do you install flash debug version with Windows 10
I have been looking for a way to install the debug version of flashplayer for ie11 or the newer microsoft edge browser under Windows 10. AS far as I understand, the flash plugin is now embedded with both browsers, so there is no way to update it to a debug version.
Using the debug version installer from adobe site (active x version), gives me a pop-up stating that I already have the latest verion which is true, but there seems to be no way to change my version with the debug one.
AS anyone succeed in using the debug version of flash undex one of these browser on Windows 10 (64bits)?

Thanks,

答:
Download the windows 7 virtual machine for free. I recommend Virtual Box. https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/

Once you have Windows 7 running inside Windows 10, install the IE Flash debugger or another of your choice. https://www.adobe.com/support/flashplayer/debug_downloads.html


问:
Starting second javascript when the first one is finished
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:  </p>

```<code>HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:
<script>
function move() {
    var elem = document.getElementById("myBar");
    var myFunc01 = function() {
    var i = 1;
    while (i < 101) {
        (function(i) {
            setTimeout(function() {
                i++;
                elem.style.width = i + '%';
                elem.innerHTML = i + '%';
            }, 600 * i)
        })(i++)
    }
    };
    myFunc01();
}
</script>
<script>
function finalize() {
    var elem = document.getElementById("myBar");
    var myFunc02 = function() {
                elem.innerHTML = 'Finalizing...';
    };
    setTimeout(myFunc02, 600);
}
</script>
</code>```

答:
Thanks James, that's it!
After some re-arranging, this is what the second script looks like. And it works as expected.</p>

```<code><script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
            elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>
</code>```

Body:
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:

HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:

Body:
Thanks James, that's it!
After some re-arranging, this is what the second script looks like. And it works as expected.

<script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
            elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>


问:
How to convert NSObject to NSDictionary or how to access NSObject key Swift3
I`m new on this I hope you can help me.

I recibe a variable in a function, this variable is a key value object and I have the next code to set this var.

```<code>let params = command.arguments[0] as? NSObject
</code>```

If I print this variable the result is:

```<code>Optional(<__NSArrayM 0x17024fea0>(
{
    coordinate = "xxxxxxx,xxxxx";
    identifier = cordstrab;
    latitude = "xxxxxxxx";
    longitude = "xxxxxxx";
    note = Trabajo;
    radius = 5;
    type = onEntry;
}
)
)
</code>```

I want to be able to acces to the data, I'm trying with

```<code>let lat = (params?.value(forKey: "latitude") as! String)
</code>```

I don´t know what is wrong or how can I get the the values of this object.

答:
Since the object seems to be an dictionary array cast it to an dictionary array and use key subscription for the dictionary

```<code>if let params = command.arguments[0] as? [[String:Any]], let dict = params.first {
   let lat = dict["latitude"] as! String // the output is clearly string
   let long = dict["longitude"] as! String
   ...
}
</code>```

Don't cast objects to NSObject in Swift unless the compiler tells you.

Body:
I`m new on this I hope you can help me.

I recibe a variable in a function, this variable is a key value object and I have the next code to set this var.

let params = command.arguments[0] as? NSObject

If I print this variable the result is:

Optional(<__NSArrayM 0x17024fea0>(
{
    coordinate = "xxxxxxx,xxxxx";
    identifier = cordstrab;
    latitude = "xxxxxxxx";
    longitude = "xxxxxxx";
    note = Trabajo;
    radius = 5;
    type = onEntry;
}
)
)

I want to be able to acces to the data, I'm trying with

let lat = (params?.value(forKey: "latitude") as! String)

I don´t know what is wrong or how can I get the the values of this object.

Body:
Since the object seems to be an dictionary array cast it to an dictionary array and use key subscription for the dictionary

if let params = command.arguments[0] as? [[String:Any]], let dict = params.first {
   let lat = dict["latitude"] as! String // the output is clearly string
   let long = dict["longitude"] as! String
   ...
}

Don't cast objects to NSObject in Swift unless the compiler tells you.


问:
Protractor Element text value sendKeys and attribute error
i've been trying to run this code in protractor but i keep getting this error also i can't find a way to get the anpr_box_input text value anyhow.

Value: ManagedPromise::871 {[[PromiseStatus]]: "pending"}
    failed - should have a valid license number plate when screen contains as ANPR request
  Suite failed: ANPR Screen Content

Chrome version: 58.0.3029.110 (64-bit)
Dependencies:
"protractor": "5.1.2",
"jasmine-core": "~2.4.1",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"@types/jasmine": "2.5.36"

describe('ANPR Screen Content', function () {

```<code>it('should have a valid license number plate when screen contains as ANPR request', function () {

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    //anpr_box_input.clear().then(function() { anpr_box_input.sendKeys('999'); }); tryed it before, didn't work
    anpr_box_input.clear().then(function() { anpr_box_input.setAttribute("value", "459"); });

    base_keyboard_ok.click();

    /* didn't work
    anpr_box_input.getText().then(function(text) {
        console.log("AQUI: " + text);
    });
    */

    //console.log("Value: " + anpr_box_input.getAttribute('value')); didn't work

    //working on..
    anpr_box_input.getAttribute('value').then(function(text) {
        console.log("Value: " + text);
    });

    //so i'll need something like
    expect(anpr_box_input.text).toEqual("1234");
});
</code>```

});

答:
Thanks very much wswebcreation, i'll have a look on what you've just mentioned about the vanila webdriver but i've just found a solution just as follows:</p>

```<code>it('should have a valid license number plate when screen contains as ANPR request', function () {
    var buttonKey;

    buttonKey = browser.driver.findElement(by.id('button_A'));
    buttonKey.click();

    browser.sleep(SLEEP_TIMER);

    buttonKey = browser.driver.findElement(by.id('button_B'));
    buttonKey.click();

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));
    base_keyboard_ok.click();

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    anpr_box_input.getAttribute('innerHTML').then(function(anpr) {
        console.log("Plate: " + anpr);
        expect(globalE2EFunctions.validateAnpr(anpr)).toBe(true);
    });

});

module.exports = {

  //Still need to implement regex plates validation according to each country patterns
  validateAnpr: function(anpr) {
    if(anpr != 'CANCEL' && anpr != 'DEL' && anpr != 'OK'){
      return true;
    } else{
        return false;
    }
  }

};
</code>```

Body:
i've been trying to run this code in protractor but i keep getting this error also i can't find a way to get the anpr_box_input text value anyhow.

Value: ManagedPromise::871 {[[PromiseStatus]]: "pending"}
    failed - should have a valid license number plate when screen contains as ANPR request
  Suite failed: ANPR Screen Content

Chrome version: 58.0.3029.110 (64-bit)
Dependencies:
"protractor": "5.1.2",
"jasmine-core": "~2.4.1",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"@types/jasmine": "2.5.36"

describe('ANPR Screen Content', function () {

it('should have a valid license number plate when screen contains as ANPR request', function () {

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    //anpr_box_input.clear().then(function() { anpr_box_input.sendKeys('999'); }); tryed it before, didn't work
    anpr_box_input.clear().then(function() { anpr_box_input.setAttribute("value", "459"); });

    base_keyboard_ok.click();

    /* didn't work
    anpr_box_input.getText().then(function(text) {
        console.log("AQUI: " + text);
    });
    */

    //console.log("Value: " + anpr_box_input.getAttribute('value')); didn't work

    //working on..
    anpr_box_input.getAttribute('value').then(function(text) {
        console.log("Value: " + text);
    });

    //so i'll need something like
    expect(anpr_box_input.text).toEqual("1234");
});

});

Body:
Thanks very much wswebcreation, i'll have a look on what you've just mentioned about the vanila webdriver but i've just found a solution just as follows:

it('should have a valid license number plate when screen contains as ANPR request', function () {
    var buttonKey;

    buttonKey = browser.driver.findElement(by.id('button_A'));
    buttonKey.click();

    browser.sleep(SLEEP_TIMER);

    buttonKey = browser.driver.findElement(by.id('button_B'));
    buttonKey.click();

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));
    base_keyboard_ok.click();

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    anpr_box_input.getAttribute('innerHTML').then(function(anpr) {
        console.log("Plate: " + anpr);
        expect(globalE2EFunctions.validateAnpr(anpr)).toBe(true);
    });

});

module.exports = {

  //Still need to implement regex plates validation according to each country patterns
  validateAnpr: function(anpr) {
    if(anpr != 'CANCEL' && anpr != 'DEL' && anpr != 'OK'){
      return true;
    } else{
        return false;
    }
  }

};


问:
Parsing XML using Objective C
I am new to Objective C programming, i need your help to solve my problem in parsing xml.
I have consumed a WCF Restful service, the service returns a xml formatted string.

The XML format is as below:

```<code><Content>
<Category Id="1" Name="Software">
 <Category Id="2" Name="Windows 7"/>
</Category>
<Category Id="3" Name="Hardware">
 <Category Id="4" Name="Printers"/>
</Category>
</Content>
</code>```

I am trying to retrieve the parent node in a array and child nodes in another array.

When i use:

```<code>NSArray *nodes=nil;
nodes=[doc nodesForXPath:@"//Category" error:nil];
</code>```

All the node details having the node Category comes in the array. But the child item of name Category should not come in parent list.

Please suggest me how to get only the parent node in a collection, and the child nodes in another collection.

答: you can use NSXMLParser for that. it is a SAX Parser. You can Find Some more Dom and SAX parser.</p>

Title: Parsing XML using Objective C

Body:
I am new to Objective C programming, i need your help to solve my problem in parsing xml.
I have consumed a WCF Restful service, the service returns a xml formatted string.

The XML format is as below:

<Content>
<Category Id="1" Name="Software">
 <Category Id="2" Name="Windows 7"/>
</Category>
<Category Id="3" Name="Hardware">
 <Category Id="4" Name="Printers"/>
</Category>
</Content>

I am trying to retrieve the parent node in a array and child nodes in another array.

When i use:

NSArray *nodes=nil;
nodes=[doc nodesForXPath:@"//Category" error:nil];

All the node details having the node Category comes in the array. But the child item of name Category should not come in parent list.

Please suggest me how to get only the parent node in a collection, and the child nodes in another collection.


问:
Deserialize a changing JSON
EDIT 1: Still hasn't been resolved ...

EDIT 2: Finally resolved! See answer below.

I want to deserialize a changing JSON in C#. With that, creating classes for it is impossible as I can't create classes for every changing piece. The objects are those who are changing, like this:

Unchanged JSON:

```<code>{
  "Class 1": {
    "Blablabla": {
       "ExampleValue1": "Example Value",
       "ExampleValue2": 500
  },
    "Blablabla-Blablabla": {
       "ExampleValue1": "Example Value",
       "ExampleValue2": 1000
}
</code>```

to this:

```<code>{
  "Class 1": {
    "Blablabla-Changed-Blablabla": {
       "ExampleValue1": "Changed Example Value",
       "ExampleValue2": 750
  },
    "Blablabla-Blablabla-Changed-Blablabla": {
       "ExampleValue1": "Changed Example Value",
       "ExampleValue2": 1125
}
</code>```

How can I do this in C#?

答:
You could use the JToken class from Newtonsoft.Json.Linq.

```<code>JToken token = JToken.Parse(json);
JToken class1 = token.SelectToken("Class1");
</code>```

Note that if you want to use spaces in fieldnames you need to use the following JSONPath notation to use the SelectToken method.

```<code>JToken token = JToken.Parse(json);
JToken class1 = token.SelectToken("['Class 1']")
</code>```

You can also dynamicly access the members and children of the JToken. For example if you want to dynamicly print the structue you can do the following

```<code>JToken token = JToken.Parse(json);
PrintChildren(token);

private void PrintChildren(JToken item)
{
    Console.WriteLine(item.Path);
    foreach(var child in item.Children())
    {
        PrintChildren(child);
    }
}
</code>```

You could also deserialize your json into a dynamic.

```<code>dynamic obj = JObject.Parse(json);
</code>```

Or

```<code>dynamic obj = JsonConvert.DeserializeObject(json)
</code>```

Title: Deserialize a changing JSON

Body:
EDIT 1: Still hasn't been resolved ...

EDIT 2: Finally resolved! See answer below.

I want to deserialize a changing JSON in C#. With that, creating classes for it is impossible as I can't create classes for every changing piece. The objects are those who are changing, like this:

Unchanged JSON:

{
  "Class 1": {
    "Blablabla": {
       "ExampleValue1": "Example Value",
       "ExampleValue2": 500
  },
    "Blablabla-Blablabla": {
       "ExampleValue1": "Example Value",
       "ExampleValue2": 1000
}

to this:

{
  "Class 1": {
    "Blablabla-Changed-Blablabla": {
       "ExampleValue1": "Changed Example Value",
       "ExampleValue2": 750
  },
    "Blablabla-Blablabla-Changed-Blablabla": {
       "ExampleValue1": "Changed Example Value",
       "ExampleValue2": 1125
}

How can I do this in C#?

Body:
You could use the JToken class from Newtonsoft.Json.Linq.

JToken token = JToken.Parse(json);
JToken class1 = token.SelectToken("Class1");

Note that if you want to use spaces in fieldnames you need to use the following JSONPath notation to use the SelectToken method.

JToken token = JToken.Parse(json);
JToken class1 = token.SelectToken("['Class 1']")

You can also dynamicly access the members and children of the JToken. For example if you want to dynamicly print the structue you can do the following

JToken token = JToken.Parse(json);
PrintChildren(token);

private void PrintChildren(JToken item)
{
    Console.WriteLine(item.Path);
    foreach(var child in item.Children())
    {
        PrintChildren(child);
    }
}

You could also deserialize your json into a dynamic.

dynamic obj = JObject.Parse(json);

Or

dynamic obj = JsonConvert.DeserializeObject(json)


问:
Wrap multiple textviews to appear as one sentence
Consider the sentence

"Mike has commented on Davids review at Pizza Planet"

This sentence may wrap onto 2 lines, but I want the words "Mike", "Davids" and "Pizza Planet clickable items".

If I use separate TextViews for each of these word, and also for the non clickable words in between, How can I do this so that they wrap nicely onto 2 lines?

答:
You can use spannable strings for your needs, check this out:

```<code>TextView textView = (TextView) findViewById(R.id.textView);

SpannableString user = new SpannableString("Mike");
ClickableSpan userClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on user
    }
};
user.setSpan(userClickableSpan, 0, user.length(),
             SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableString commentedOnUser = new SpannableString("Davids");
ClickableSpan commentedOnUserClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on commentedOnUser
    }
};
commentedOnUser.setSpan(commentedOnUserClickableSpan, 0, commentedOnUser.length(),
                        SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableString place = new SpannableString("Pizza Planet");
ClickableSpan placeClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on place
    }
};
place.setSpan(placeClickableSpan, 0, place.length(),
              SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
textView.setText(user);
textView.append(" is has commented on ");
textView.append(commentedOnUser);
textView.append(" review at ");
textView.append(place);
</code>```

Now when it's all part of one TextView, use "\n" to break the line.

Body:
You can use spannable strings for your needs, check this out:

TextView textView = (TextView) findViewById(R.id.textView);

SpannableString user = new SpannableString("Mike");
ClickableSpan userClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on user
    }
};
user.setSpan(userClickableSpan, 0, user.length(),
             SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableString commentedOnUser = new SpannableString("Davids");
ClickableSpan commentedOnUserClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on commentedOnUser
    }
};
commentedOnUser.setSpan(commentedOnUserClickableSpan, 0, commentedOnUser.length(),
                        SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableString place = new SpannableString("Pizza Planet");
ClickableSpan placeClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //click on place
    }
};
place.setSpan(placeClickableSpan, 0, place.length(),
              SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
textView.setText(user);
textView.append(" is has commented on ");
textView.append(commentedOnUser);
textView.append(" review at ");
textView.append(place);

Now when it's all part of one TextView, use "\n" to break the line.


问:
ReactiveX concat doesn't produce onNext from first observable if second fails immediately
I concat two observables to display data from cache firstly and after that start loading data from the network and show updated data.

```<code>Observable.concat(
    getContentFromCache.subscribeOn(dbScheduler),
    getContentFromNetwork.subscibeOn(networkScheduler)
).observeOn(AndroidSchedulers.mainThread())
 .subscribe(subscriber);
</code>```

If there is no network connection the second observable fails immediately after OnSubscribe is called.

In case the second observable fails immediately, data from first observable is lost. The onNext method is never called in the subscriber.

I think, this might be due to the following code in the OperatorConcat.ConcatSubscriber

```<code>    @Override
    public void onNext(Observable<? extends T> t) {
        queue.add(nl.next(t));
        if (WIP_UPDATER.getAndIncrement(this) == 0) {
            subscribeNext();
        }
    }

    @Override
    public void onError(Throwable e) {
        child.onError(e);
        unsubscribe();
    }
</code>```

Looks like after error is received it unsubscribes, and all pending onNext are lost.

What is the best way to solve my problem?

Update

Looks like I have found the solution, instead of setting observOn for concatenated observable I set observOn for each observable.

```<code>Observable.concat(
    getContentFromCache.subscribeOn(dbScheduler).observeOn(AndroidSchedulers.mainThread()),
    getContentFromNetwork.subscibeOn(networkScheduler).observeOn(AndroidSchedulers.mainThread())
)
 .subscribe(subscriber);
</code>```

答:
Default behavior of observeOn is that onError events can jump in front of the queue, here is the quote from the docs:

Note that onError notifications will cut ahead of onNext notifications
  on the emission thread if Scheduler is truly asynchronous.

Here is small test to illustrate the thing:

```<code>Scheduler newThreadScheduler = Schedulers.newThread();

Observable<Integer> stream = Observable.create(integerEmitter -> {
    integerEmitter.onNext(1);
    integerEmitter.onNext(2);
    integerEmitter.onNext(3);
    integerEmitter.onNext(4);
    integerEmitter.onNext(5);
    integerEmitter.onError(new RuntimeException());
}, Emitter.BackpressureMode.NONE);

TestSubscriber<Integer> subscriber = new TestSubscriber<>();
stream.subscribeOn(Schedulers.computation())
        .observeOn(newThreadScheduler).subscribe(subscriber);

subscriber.awaitTerminalEvent();

subscriber.assertValues(1, 2, 3, 4, 5);
subscriber.assertError(RuntimeException.class);
</code>```

Normally consumer would expect the following sequence: 1 > 2 > 3 > 4 > 5 > Error. But using just observeOn may put error ahead and test will fail.

This behavior was implemented long time ago here https://github.com/ReactiveX/RxJava/issues/1680, check for the motivation why it was done like that. To avoid such behavior one can use overloaded observeOn with delayError parameter:

indicates if the onError notification may not cut ahead of onNext
  notification on the other side of the scheduling boundary. If true a sequence ending in onError will be replayed in the same order as was received
  from upstream

This is what you normally expect, so changing observeOn(newThreadScheduler) to observeOn(newThreadScheduler, true) will fix the test.

Then to the question of @Neil: why solution proposed by @Rostyslav is working? It is working, because there is no thread switch for the final sequence.

In the proposed solution final sequence is crafted from two sequences on the same thread: 1st sequence is data from cache, 2nd sequence is just error from network. They are crafted together on the same thread and after there is no thread switch - subscriber observes on the AndroidSchedulers.mainThread(). If you try to change final Scheduler to some other, it will fail again.

Body:
I concat two observables to display data from cache firstly and after that start loading data from the network and show updated data.

Observable.concat(
    getContentFromCache.subscribeOn(dbScheduler),
    getContentFromNetwork.subscibeOn(networkScheduler)
).observeOn(AndroidSchedulers.mainThread())
 .subscribe(subscriber);

If there is no network connection the second observable fails immediately after OnSubscribe is called.

In case the second observable fails immediately, data from first observable is lost. The onNext method is never called in the subscriber.

I think, this might be due to the following code in the OperatorConcat.ConcatSubscriber

    @Override
    public void onNext(Observable<? extends T> t) {
        queue.add(nl.next(t));
        if (WIP_UPDATER.getAndIncrement(this) == 0) {
            subscribeNext();
        }
    }

    @Override
    public void onError(Throwable e) {
        child.onError(e);
        unsubscribe();
    }

Looks like after error is received it unsubscribes, and all pending onNext are lost.

What is the best way to solve my problem?

Update

Looks like I have found the solution, instead of setting observOn for concatenated observable I set observOn for each observable.

Observable.concat(
    getContentFromCache.subscribeOn(dbScheduler).observeOn(AndroidSchedulers.mainThread()),
    getContentFromNetwork.subscibeOn(networkScheduler).observeOn(AndroidSchedulers.mainThread())
)
 .subscribe(subscriber);

Body:
Default behavior of observeOn is that onError events can jump in front of the queue, here is the quote from the docs:

Note that onError notifications will cut ahead of onNext notifications
  on the emission thread if Scheduler is truly asynchronous.

Here is small test to illustrate the thing:

Scheduler newThreadScheduler = Schedulers.newThread();

Observable<Integer> stream = Observable.create(integerEmitter -> {
    integerEmitter.onNext(1);
    integerEmitter.onNext(2);
    integerEmitter.onNext(3);
    integerEmitter.onNext(4);
    integerEmitter.onNext(5);
    integerEmitter.onError(new RuntimeException());
}, Emitter.BackpressureMode.NONE);

TestSubscriber<Integer> subscriber = new TestSubscriber<>();
stream.subscribeOn(Schedulers.computation())
        .observeOn(newThreadScheduler).subscribe(subscriber);

subscriber.awaitTerminalEvent();

subscriber.assertValues(1, 2, 3, 4, 5);
subscriber.assertError(RuntimeException.class);

Normally consumer would expect the following sequence: 1 > 2 > 3 > 4 > 5 > Error. But using just observeOn may put error ahead and test will fail.

This behavior was implemented long time ago here https://github.com/ReactiveX/RxJava/issues/1680, check for the motivation why it was done like that. To avoid such behavior one can use overloaded observeOn with delayError parameter:

indicates if the onError notification may not cut ahead of onNext
  notification on the other side of the scheduling boundary. If true a sequence ending in onError will be replayed in the same order as was received
  from upstream

This is what you normally expect, so changing observeOn(newThreadScheduler) to observeOn(newThreadScheduler, true) will fix the test.

Then to the question of @Neil: why solution proposed by @Rostyslav is working? It is working, because there is no thread switch for the final sequence.

In the proposed solution final sequence is crafted from two sequences on the same thread: 1st sequence is data from cache, 2nd sequence is just error from network. They are crafted together on the same thread and after there is no thread switch - subscriber observes on the AndroidSchedulers.mainThread(). If you try to change final Scheduler to some other, it will fail again.


问:
WordPress get post thumbnail and wrap it in permalink
I would like to get the post thumbnail and link it to the post in WordPress. This seems logical to me but it's not producing the desired result.

```<code><?php
    if(is_category()){
        echo '<a href="' . get_permalink() . '">' . '<img src="' . the_post_thumbnail( 'full' ) . '"</a>';
    }
?>
</code>```

Instead, it's producing this in the DOM:

What do I need to do to get this working?

答:
Have you tried the 'get_the_post_thumbnail_url()' function? As described on this page https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/

Also I'm not sure if the 'full' size is correct, maybe first try it without the optional size parameter. This only works while "in the loop", or you'll have to specify the post ID as the first parameter.

You might want to create an if statement to display the post tile if there isn't a post thumbnail (the function returns false if this is the case).

```<code><?php
if(is_category()){
    echo '<a href="' . get_permalink() . '">' . '<img src="' . get_the_post_thumbnail_url( 'full' ) . '"/></a>';
}
?>
</code>```

Body:
I would like to get the post thumbnail and link it to the post in WordPress. This seems logical to me but it's not producing the desired result.

<?php
    if(is_category()){
        echo '' . '<img src="' . the_post_thumbnail( 'full' ) . '"';
    }
?>

Instead, it's producing this in the DOM:

What do I need to do to get this working?

Body:
Have you tried the 'get_the_post_thumbnail_url()' function? As described on this page https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/

Also I'm not sure if the 'full' size is correct, maybe first try it without the optional size parameter. This only works while "in the loop", or you'll have to specify the post ID as the first parameter.

You might want to create an if statement to display the post tile if there isn't a post thumbnail (the function returns false if this is the case).

<?php
if(is_category()){
    echo '<a href="' . get_permalink() . '">' . '<img src="' . get_the_post_thumbnail_url( 'full' ) . '"/></a>';
}
?>


问:
Use gremlin traversals (Tinkergraph) against the gremlin server
Is it possible to use Tinkergraph-Gremlin against a local instance of the gremlin-server?
In other words, what's missing from the following source code to make it query the localhost:8182 gremlin-server instead of the in-memory DB:</p>

```<code>Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
</code>```

答:
Sounds like you want to use a remote traversal.

```<code>EmptyGraph graph = EmptyGraph.instance();
GraphTraversalSource g = graph.traversal().withRemote("conf/remote-graph.properties");
</code>```

Check out the TinkerPop documentation for Connecting via withRemote().

Body:
Is it possible to use Tinkergraph-Gremlin against a local instance of the gremlin-server?
In other words, what's missing from the following source code to make it query the localhost:8182 gremlin-server instead of the in-memory DB:

Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();

Body:
Sounds like you want to use a remote traversal.

EmptyGraph graph = EmptyGraph.instance();
GraphTraversalSource g = graph.traversal().withRemote("conf/remote-graph.properties");

Check out the TinkerPop documentation for Connecting via withRemote().


问:
MySQL: Select comments and the number of replies they have
I have a 'Comments' MySQL table that has the following fields:

id

text

parent_id (NULL by default)

Basically I want to select all the comments that have a NULL parent_id, and the total number of their replies. This comment system has only one level of replies. The result would look something like:

```<code>-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------
</code>```

Appreciate your help :)

答:
This would probably be someting like:

```<code>select c.id, c.Text, count(reply.id) as total_replies
from comments c
left join comments reply on c.id = reply.parent_id
where c.parent_id is null
group by c.id
</code>```

If I understand correctly that the comments and replies are in the same table.

Body:
I have a 'Comments' MySQL table that has the following fields:

id

text

parent_id (NULL by default)

Basically I want to select all the comments that have a NULL parent_id, and the total number of their replies. This comment system has only one level of replies. The result would look something like:

-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------

Appreciate your help :)

Body:
This would probably be someting like:

select c.id, c.Text, count(reply.id) as total_replies
from comments c
left join comments reply on c.id = reply.parent_id
where c.parent_id is null
group by c.id

If I understand correctly that the comments and replies are in the same table.


问:
Factory with Composite or Abstract Factory
I have following class hierarchy:

public interface RateSheetProductExtractor
{
  List<ProductData> extract(SGQuotingData quotingData);
}

@Service
@Scope("requestjob")
public class ProductExtractorFactory
{
  @Autowired
  private OptionalRatingProductExtractorFactory optionalRatingProductExtractorFactory;
  @Autowired
  private QuotePlanProductExtractorFactory quotePlanProductExtractorFactory;
  @Autowired
  private AlternateProductExtractorFactory alternateProductExtractorFactory;

  public RateSheetProductExtractor getProductExtractor(
    TablePlanType tablePlanType,
    TableRatingType ratingType)
  {
    switch (tablePlanType)
    {
      case QUOTED:
        return quotePlanProductExtractorFactory.getInstance(ratingType);
      case OPTIONAL:
        return optionalRatingProductExtractorFactory.getInstance(ratingType);
      case ALTERNATE:
        return alternateProductExtractorFactory.getInstance(ratingType);
      default:
        throw new IllegalArgumentException(tablePlanType + " is unsupported yet.");
    }
  }
}

@Service
@Scope("requestjob")
public class OptionalRatingProductExtractorFactory
{
  @Autowired
  private AcaProductExtractor acaProductExtractor;
  @Autowired
  private AgeRatedAsCompositeProductExtractor ageRatedAsCompositeProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedAsCompositeProductExtractor;
      case COMPOSITE:
        return acaProductExtractor;
      default:
        throw new IllegalArgumentException(
          "Product extractor isn't defined for optional plan type and rating type " + ratingType);

    }
  }
}

@Service
@Scope("requestjob")
public class QuotePlanProductExtractorFactory
{
  @Autowired
  private GfProductExtractor gfExtractor;
  @Autowired
  private AgeRatedProductExtractor ageRatedProductExtractor;
  @Autowired
  private MedicalProductExtractor medicalProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedProductExtractor;
      case COMPOSITE_AGE:
        return gfExtractor;
      case COMPOSITE:
        return medicalProductExtractor;
      default:
        throw new IllegalArgumentException(
          ratingType + " is unsupported for QuotePlan product extractor factory.");
    }
  }
}

@Service
@Scope("requestjob")
public class AlternateProductExtractorFactory
{
  @Autowired
  private AlternateAgeRatedProductExtractor ageRatedProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    if (ratingType == AGE)
    {
      return ageRatedProductExtractor;
    }
    throw new IllegalArgumentException(
      ratingType + " is unsupported for QuotePlan product extractor factory.");
  }
}```

would it be correct to call ProductExtractorFactory as AbstractProductExtractorFactory(based on the appropriate pattern)? or it's more like a simple factory of factories?

Sorry for huge listing...:)

答: My two cents is to keep the name as it is. I am not sure about your workplace but at my previous organizations we used to keep the class name as AbstractSomeClass if it was an abstract class and a concrete class has to implement its methods. If you check the Java Collections API also, all classes starting with Abstract has more to do with this concept rather than the design pattern.

Body:
I have following class hierarchy:

public interface RateSheetProductExtractor
{
  List<ProductData> extract(SGQuotingData quotingData);
}

@Service
@Scope("requestjob")
public class ProductExtractorFactory
{
  @Autowired
  private OptionalRatingProductExtractorFactory optionalRatingProductExtractorFactory;
  @Autowired
  private QuotePlanProductExtractorFactory quotePlanProductExtractorFactory;
  @Autowired
  private AlternateProductExtractorFactory alternateProductExtractorFactory;

  public RateSheetProductExtractor getProductExtractor(
    TablePlanType tablePlanType,
    TableRatingType ratingType)
  {
    switch (tablePlanType)
    {
      case QUOTED:
        return quotePlanProductExtractorFactory.getInstance(ratingType);
      case OPTIONAL:
        return optionalRatingProductExtractorFactory.getInstance(ratingType);
      case ALTERNATE:
        return alternateProductExtractorFactory.getInstance(ratingType);
      default:
        throw new IllegalArgumentException(tablePlanType + " is unsupported yet.");
    }
  }
}

@Service
@Scope("requestjob")
public class OptionalRatingProductExtractorFactory
{
  @Autowired
  private AcaProductExtractor acaProductExtractor;
  @Autowired
  private AgeRatedAsCompositeProductExtractor ageRatedAsCompositeProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedAsCompositeProductExtractor;
      case COMPOSITE:
        return acaProductExtractor;
      default:
        throw new IllegalArgumentException(
          "Product extractor isn't defined for optional plan type and rating type " + ratingType);

    }
  }
}

@Service
@Scope("requestjob")
public class QuotePlanProductExtractorFactory
{
  @Autowired
  private GfProductExtractor gfExtractor;
  @Autowired
  private AgeRatedProductExtractor ageRatedProductExtractor;
  @Autowired
  private MedicalProductExtractor medicalProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    switch (ratingType)
    {
      case AGE:
        return ageRatedProductExtractor;
      case COMPOSITE_AGE:
        return gfExtractor;
      case COMPOSITE:
        return medicalProductExtractor;
      default:
        throw new IllegalArgumentException(
          ratingType + " is unsupported for QuotePlan product extractor factory.");
    }
  }
}

@Service
@Scope("requestjob")
public class AlternateProductExtractorFactory
{
  @Autowired
  private AlternateAgeRatedProductExtractor ageRatedProductExtractor;

  public RateSheetProductExtractor getInstance(TableRatingType ratingType)
  {
    if (ratingType == AGE)
    {
      return ageRatedProductExtractor;
    }
    throw new IllegalArgumentException(
      ratingType + " is unsupported for QuotePlan product extractor factory.");
  }
}

would it be correct to call ProductExtractorFactory as AbstractProductExtractorFactory(based on the appropriate pattern)? or it's more like a simple factory of factories?

Sorry for huge listing...:)


问:
Identifier not found.C3861
I have a file "HSlider.h" it is using "Draw.h",where I defined my functions to use them .
But compiler says I havent defined them(identificator not found).I searched forums for similiar error,but it didnt help.

I am working in VS 2015 Communty .

ERROR EXAMPLE:
Error C3861 DrawGUIBox: identifier not found
Try2 c:\users\lel\documents\visual studio 2015\projects\try2\try2\hslider.h 50
.

HSlider.h

```<code>#include <string>
#include <iostream>
#include <map>
#include <iterator>
#include <conio.h>
#include "Offsets.h"

#include "Draw.h"
using namespace std;

class Button
{
public:
    void Init(float _x, float _y, float _w, float _h, int _r, int _g, int _b, int _a, int _rr, int _gg, int _bb, int _aa,int _onr,int _ong,int _onb)
    {
        x = _x;
        y = _y;
        w = _w;
        h = _h;
        r = _r;
        g = _g;
        b = _b;
        a = _a;
        rr = _rr;
        gg = _gg;
        bb = _bb;
        aa = _aa;
        onr = _onr;
        onb = _onb;
        ong = _ong;

    }
    void Move(float _x, float _y)
    {
        x = _x;
        y = _y;
    }
    void Update(int _bindb)
    {
        BindB = _bindb;
        DrawGUIBox(x, y, w, h, r, g, b, a, rr, gg, bb, aa);
        POINT p;
        GetCursorPos(&p);

        if ((p.x > x&&p.x<x + w&&p.y>y&&p.y < y + h))
        {
            if ((GetAsyncKeyState(VK_LBUTTON)&1 ))
            {
                On = !On;

            }

        }
        if ((GetAsyncKeyState(BindB)&1 ))
        {
            On = !On;
        }
        if (On)
        {
            DrawGUIBox(x, y, w, h, r, g, b, a, onr,ong,onb, a);
        }

    }
    bool Extract()
    {
        return On;
    }
    void Off()
    {
        On = false;
    }
private:
    float x;
    float y;
    float w;
    float h;
    int r;
    int g;
    int b;
    int a;
    int rr;
    int gg;
    int bb;
    int aa;
    int onr;
    int ong;
    int onb;
    int BindB;
    bool On = false;
    bool IsUP = true;
};
</code>```

Draw.h

```<code>  #pragma once
    #ifndef HDRAWFUNC_H
    #define HDRAWFUNC_H

    #include "DirectX.h"

    #pragma warning( disable : 4244 ) //remove the incoming warns
    #pragma warning( disable : 4996 ) //remove the incoming warns

    #include <d3dx9.h>
    #include <d3d9.h>
    #define D3DFVF_TL (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)
    #pragma comment(lib, "d3d9.lib")
    #pragma comment(lib, "d3dx9.lib")
    static struct D3DTLVERTEX;
    void GradientFunc(int x, int y, int w, int h, int r, int g, int b, int a);
    void DrawCenterLine(float x, float y, int r, int g, int b, int a);
    void DrawLine(float x, float y, float xx, float yy, int r, int g, int b, int a);
    void DrawCursorLine(float x, float y, float xx, float yy, int r, int g, int b, int a);
    void FillRGB(float x, float y, float w, float h, int r, int g, int b, int a);
    void DrawBox(float x, float y, float width, float height, float px, int r, int g, int b, int a);
    void DrawGUIBox(float x, float y, float w, float h, int r, int g, int b, int a, int rr, int gg, int bb, int aa);
    void DrawHealthBar(float x, float y, float w, float h, int r, int g, int b);
    void DrawHealthBarBack(float x, float y, float w, float h);
    void DrawGroupBox(float x, float y, float w, float h, int r, int g, int b, int a, int rr, int gg, int bb, int aa, char* title);
    int DrawString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont);
    int DrawShadowString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont);
    void DrawCircle(int x, int y, float radius, int Sides, D3DCOLOR color);
    D3DTLVERTEX CreateD3DTLVERTEX(float X, float Y, float Z, float RHW, D3DCOLOR color, float U, float V);
    void DrawFilledCircle(int xPos, int yPos, int Radius, D3DCOLOR color);
    void FillARGBTriangle(int x1, int y1, int x2, int y2, int x3, int y3, D3DCOLOR color, IDirect3DDevice9 *pDevice);
    #endif
</code>```

And whole project if you need it. https://yadi.sk/d/uOPt8pdC3Jb78o

答:
The problem is not in your source code. The problem is that your Visual Studio solution file (in the link you posted) has become corrupted. In the solution file there are references to a project called Try2, but this project does not exist in the solution.

To fix this, do the following.

Open the Help.sln file with notepad++, and you will see there is a line

```<code>Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Try2", "Try2\Try2.vcxproj", "{BC659ABD-F853-4678-83AF-3D29339A7FC0}"
</code>```

This means that there is meant to be a sub-project called Try2, but it doesn't exist. In your archive, the sub-project is actually called "Help". So, change the line to:

```<code>Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Help", "Help\Help.vcxproj", "{BC659ABD-F853-4678-83AF-3D29339A7FC0}"
</code>```

After that, go through the x64 folders in your solution and remove any residual files that refer to Try2.

OR, create a new empty solution and copy your .cpp and .h source files (only) one at a time into the new solution.

(There is also a separate problem where the Offsets.h file is missing, but I can't help with that.)

Title: Identifier not found.C3861

Body:
I have a file "HSlider.h" it is using "Draw.h",where I defined my functions to use them .
But compiler says I havent defined them(identificator not found).I searched forums for similiar error,but it didnt help.

I am working in VS 2015 Communty .

ERROR EXAMPLE:
Error C3861 DrawGUIBox: identifier not found
Try2 c:\users\lel\documents\visual studio 2015\projects\try2\try2\hslider.h 50
.

HSlider.h

#include <string>
#include <iostream>
#include <map>
#include <iterator>
#include <conio.h>
#include "Offsets.h"

#include "Draw.h"
using namespace std;

class Button
{
public:
    void Init(float _x, float _y, float _w, float _h, int _r, int _g, int _b, int _a, int _rr, int _gg, int _bb, int _aa,int _onr,int _ong,int _onb)
    {
        x = _x;
        y = _y;
        w = _w;
        h = _h;
        r = _r;
        g = _g;
        b = _b;
        a = _a;
        rr = _rr;
        gg = _gg;
        bb = _bb;
        aa = _aa;
        onr = _onr;
        onb = _onb;
        ong = _ong;

    }
    void Move(float _x, float _y)
    {
        x = _x;
        y = _y;
    }
    void Update(int _bindb)
    {
        BindB = _bindb;
        DrawGUIBox(x, y, w, h, r, g, b, a, rr, gg, bb, aa);
        POINT p;
        GetCursorPos(&p);

        if ((p.x > x&&p.x<x + w&&p.y>y&&p.y < y + h))
        {
            if ((GetAsyncKeyState(VK_LBUTTON)&1 ))
            {
                On = !On;

            }

        }
        if ((GetAsyncKeyState(BindB)&1 ))
        {
            On = !On;
        }
        if (On)
        {
            DrawGUIBox(x, y, w, h, r, g, b, a, onr,ong,onb, a);
        }

    }
    bool Extract()
    {
        return On;
    }
    void Off()
    {
        On = false;
    }
private:
    float x;
    float y;
    float w;
    float h;
    int r;
    int g;
    int b;
    int a;
    int rr;
    int gg;
    int bb;
    int aa;
    int onr;
    int ong;
    int onb;
    int BindB;
    bool On = false;
    bool IsUP = true;
};

Draw.h

  #pragma once
    #ifndef HDRAWFUNC_H
    #define HDRAWFUNC_H

    #include "DirectX.h"

    #pragma warning( disable : 4244 ) //remove the incoming warns
    #pragma warning( disable : 4996 ) //remove the incoming warns

    #include <d3dx9.h>
    #include <d3d9.h>
    #define D3DFVF_TL (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)
    #pragma comment(lib, "d3d9.lib")
    #pragma comment(lib, "d3dx9.lib")
    static struct D3DTLVERTEX;
    void GradientFunc(int x, int y, int w, int h, int r, int g, int b, int a);
    void DrawCenterLine(float x, float y, int r, int g, int b, int a);
    void DrawLine(float x, float y, float xx, float yy, int r, int g, int b, int a);
    void DrawCursorLine(float x, float y, float xx, float yy, int r, int g, int b, int a);
    void FillRGB(float x, float y, float w, float h, int r, int g, int b, int a);
    void DrawBox(float x, float y, float width, float height, float px, int r, int g, int b, int a);
    void DrawGUIBox(float x, float y, float w, float h, int r, int g, int b, int a, int rr, int gg, int bb, int aa);
    void DrawHealthBar(float x, float y, float w, float h, int r, int g, int b);
    void DrawHealthBarBack(float x, float y, float w, float h);
    void DrawGroupBox(float x, float y, float w, float h, int r, int g, int b, int a, int rr, int gg, int bb, int aa, char* title);
    int DrawString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont);
    int DrawShadowString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont);
    void DrawCircle(int x, int y, float radius, int Sides, D3DCOLOR color);
    D3DTLVERTEX CreateD3DTLVERTEX(float X, float Y, float Z, float RHW, D3DCOLOR color, float U, float V);
    void DrawFilledCircle(int xPos, int yPos, int Radius, D3DCOLOR color);
    void FillARGBTriangle(int x1, int y1, int x2, int y2, int x3, int y3, D3DCOLOR color, IDirect3DDevice9 *pDevice);
    #endif

And whole project if you need it. https://yadi.sk/d/uOPt8pdC3Jb78o

Body:
The problem is not in your source code. The problem is that your Visual Studio solution file (in the link you posted) has become corrupted. In the solution file there are references to a project called Try2, but this project does not exist in the solution.

To fix this, do the following.

Open the Help.sln file with notepad++, and you will see there is a line

Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Try2", "Try2\Try2.vcxproj", "{BC659ABD-F853-4678-83AF-3D29339A7FC0}"

This means that there is meant to be a sub-project called Try2, but it doesn't exist. In your archive, the sub-project is actually called "Help". So, change the line to:

Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Help", "Help\Help.vcxproj", "{BC659ABD-F853-4678-83AF-3D29339A7FC0}"

After that, go through the x64 folders in your solution and remove any residual files that refer to Try2.

OR, create a new empty solution and copy your .cpp and .h source files (only) one at a time into the new solution.

(There is also a separate problem where the Offsets.h file is missing, but I can't help with that.)


问:
Save XML string from urllib python
Im trying to save a xml that I fetched from a Url (from google maps API) and I get argument must be str, not bytes, here is the code</p>

```<code>con=urllib.request.urlopen("https://maps.googleapis.com/maps/api/geocode/xml?address=Limon,CR&key=AIzaSyBeR0hUS1myPd7oa2LjJ2F6Vl37b-rUfVo")
def saveXml:
    data=con.read()
    f=open("xml2.xml","a")
    f.write(data)
</code>```

答:
Either open the file in binary mode:

```<code>def saveXml():
    data = con.read()
    with open('xml2.xml', 'ab') as f:
        f.write(data)
</code>```

Or convert the binary data to text (if you know the encoding is, say, UTF-8.)

```<code>def saveXml():
    data = con.read().decode('UTF-8')
    with open('xml2.xml', 'a') as f:
        f.write(data)
</code>```

Title: Save XML string from urllib python

Body:
Im trying to save a xml that I fetched from a Url (from google maps API) and I get argument must be str, not bytes, here is the code

con=urllib.request.urlopen("https://maps.googleapis.com/maps/api/geocode/xml?address=Limon,CR&key=AIzaSyBeR0hUS1myPd7oa2LjJ2F6Vl37b-rUfVo")
def saveXml:
    data=con.read()
    f=open("xml2.xml","a")
    f.write(data)

Body:
Either open the file in binary mode:

def saveXml():
    data = con.read()
    with open('xml2.xml', 'ab') as f:
        f.write(data)

Or convert the binary data to text (if you know the encoding is, say, UTF-8.)

def saveXml():
    data = con.read().decode('UTF-8')
    with open('xml2.xml', 'a') as f:
        f.write(data)


问:
IIS express, access to large video
I'm using IIS Express, which installed with VS17.

Currently i'm developing asp.net mvc application, which allows users to upload large videos (e.g. 1.5 hours and 4 GB).
For develop i'm using git.

Situation:
In last release my web app allows to play videos on iis (by direct link, e.g. localhost:PORT/Videos/FILENAME.mp4) - these vids are uploaded from users;

From last release i made some changes, which doesn't touch IIS configuration and video module.
But i've got error: Now when i'm tryin' to play video by direct link i'm getting nothing (default html player cant play video [image])

And in dev console (chrome) message:

Resource interpreted as Document but transferred with MIME type video/mp4: "http://localhost:PORT/Videos/FILENAME.mp4"

Video file is OK (not corrupted).

答:
I had this same problem with IIS Express and VS 2017 on Chrome. Other browsers play the video fine. I tried to isolate the issue and created a single html page with just a video tag. Chrome will play the video if you open the HTML directly without using IIS Express.

After that I just moved the project from IIS Express to IIS and the problem was solved.

If you can, move it to IIS. The issue I believe is with IIS Express only.

Title: IIS express, access to large video


问:
Prevent robots from coping images from a website
I have a website created in PHP technology and i want to prevent robots from coping images from the website.What is the best way to prevent robots from coping images from a website?

Please make sure it doesn't harm SEO.
Please make sure this does not influence spyders and crawlers from indexing the site.

答:
Not sure if it'd work, but if you have all your images in /images/ folder maybe you could set</p>

```<code>User-agent: *
Disallow: /images/
</code>```

Body:
Not sure if it'd work, but if you have all your images in /images/ folder maybe you could set

User-agent: *
Disallow: /images/


问:
Create csv(s) from xlsx
How can I bulk convert excel files (xlsx) to csv? I tried

```<code>$source = 'C:\path\to\file'

Get-ChildItem $source '*.xlsx' | Rename-Item -NewName { $_.Name -replace '\.xlsx','.csv' }
</code>```

but the csvs were unreadable. Ideally, I'd like to be able to make a csv from each sheet (so I don't have to separate them manually before converting).

Thanks.

答:
This is what I found/got:</p>

```<code>$source = 'C:\path\to\file'

Function ExcelCSV ($File)
{
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $false
    $Excel.DisplayAlerts = $false
    $wb = $Excel.Workbooks.Open($File.FullName)
    foreach ($ws in $wb.Worksheets)
        {
        $ws.SaveAs(($Files.FullName -replace ".xlsx$","") + ".csv", 6)
        }
        $wb = $Excel.Workbooks.Close()
        $Excel.Quit()
}

Foreach ($Files in (Get-ChildItem -Path $source -Filter "*.xlsx"))
{
    ExcelCSV($Files)
}
</code>```

Title: Create csv(s) from xlsx

Body:
How can I bulk convert excel files (xlsx) to csv? I tried

$source = 'C:\path\to\file'

Get-ChildItem $source '*.xlsx' | Rename-Item -NewName { $_.Name -replace '\.xlsx','.csv' }

but the csvs were unreadable. Ideally, I'd like to be able to make a csv from each sheet (so I don't have to separate them manually before converting).

Thanks.

Body:
This is what I found/got:

$source = 'C:\path\to\file'

Function ExcelCSV ($File)
{
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $false
    $Excel.DisplayAlerts = $false
    $wb = $Excel.Workbooks.Open($File.FullName)
    foreach ($ws in $wb.Worksheets)
        {
        $ws.SaveAs(($Files.FullName -replace ".xlsx$","") + ".csv", 6)
        }
        $wb = $Excel.Workbooks.Close()
        $Excel.Quit()
}

Foreach ($Files in (Get-ChildItem -Path $source -Filter "*.xlsx"))
{
    ExcelCSV($Files)
}