问:
Vue + VUEX + Typescript + Vue Router. component not destroyed
Vue.js version = 2.3.3

Question to everybody.
I have json which contains a list of data, based on the json I create form inputs. The form inputs have a model binded, which basically updates app state trough commits.

I have a component which renders a list of checkboxes,
On one page I have 1 instance and on the next one I have 3 instances of the component, each of them have their list of checkboxes, and a different name.

When going from page 1 to page 2, the checkbox_list component from page 1 doesn't fire the destroyed lifecycle hook (other components do fire this).

On page 2 I have 3 other components of type checkbox_list with their name, model and options. (data is initialized as a function).
Somehow the third component of type checkbox list doesn't fire the created hook, neither mounted or w/e. It is rendered but doesn't and events and the model is there, and from vue debugger the model array is empty.
The problem is that when I update checkbox model (by clicking on one of the checkboxes from the list) in the 3rd component instance (the one which didn't fire the created lifecycle hook) the model contains everything I've checked on the first page of the checkbox_list component instance.

The components are basically rendered in a loop as of the data is parsed.
Anybody any ideas why does this happen?
Thanks.

Please see bellow code of my components.
InputTypes.ts

```<code>import Vue from 'vue';
import Component from 'vue-class-component';

import TextInput from './text/TextInput.vue';
import EmailInput from './email/EmailInput.vue';
import RadioGroup from './radio/RadioGroup.vue';
import SelectInput from './select/SelectInput.vue';
import SelectAutocompleteInput from './select/SelectAutocompleteInput.vue';
import PasswordInput from './password/PasswordInput.vue';
import CheckboxGroup from './checkbox/CheckboxGroup.vue';
import AgreementSection from './custom/AgreementSection.vue';
import CvSection from './custom/CVSection.vue';
import SubmitSection from './custom/SubmitSection.vue';

@Component({
  name: 'input-types',
  props: ['field', 'lastPageIndex'],
  components: {
    TextInput,
    EmailInput,
    RadioGroup,
    SelectInput,
    SelectAutocompleteInput,
    PasswordInput,
    AgreementSection,
    CheckboxGroup,
    CvSection,
    SubmitSection
  },
  watch: {
    '$route'($to, $from) {
      let clearFields = this['clearFields'];
      clearFields();
    }
  }
})

export default class InputsTypes extends Vue {
  conditionalFields: object = {fields: []};

  clearFields(): void {
    this.$set(this.conditionalFields, 'fields', []);
  }

  changeHandler(fields): void {
    this.$set(this.conditionalFields, 'fields', fields);
  }

  updateModelValue(data): void {
    console.log(data);
  }
}
</code>```

InputTypes.vue

```<code><!-- InputTypesComponent -->
<template>
  <div>
    <text-input v-if="field.type == 'text'" :field="field"></text-input>

    <email-input v-else-if="field.type == 'email'" :field="field"></email-input>

    <checkbox-group v-else-if="field.type == 'checkbox_list'" :field="field"></checkbox-group>

    <radio-group v-else-if="field.type == 'radio'" :field="field" :onChange="changeHandler"></radio-group>

    <select-input  v-else-if="field.type == 'select'" :field="field" :onChange="changeHandler"></select-input>

    <select-autocomplete-input  v-else-if="field.type == 'select_autocomplete'" :field="field" :onChange="changeHandler"></select-autocomplete-input>

    <password-input v-else-if="field.type == 'password'" :field="field"></password-input>

    <agreement-section v-else-if="field.type == 'agreement'" :field="field"></agreement-section>

    <div v-else-if="field.type == 'complex_inputs'">
      <label>{{field.label}}</label>
      <div v-for="option, key in field.options" :key="key">
        <input-types :field="option" :onChange="changeHandler"></input-types>
      </div>
    </div>
    <cv-section v-else-if="field.type == 'cv_section'" :field="field"></cv-section>
    <submit-section v-else-if="field.type == 'next_page'" :field="field" :lastPageIndex="lastPageIndex"></submit-section>

    <div v-if="conditionalFields.fields" v-for="field, key in conditionalFields.fields" :key="key">
      <input-types :field="field" :onChange="changeHandler"></input-types>
    </div>
  </div>
</template>

<script lang="ts">
  import InputsTypes from './InputsTypes.ts'
  export default InputsTypes
</script>
</code>```

CheckboxGroup.ts

```<code>import Vue from 'vue';
import Component from 'vue-class-component';

@Component({
  name: 'checkbox-group',
  props: ['field'],
  watch: {
    selected: (e) => {
      console.log(e);
    }
  },
  created(): void {
    let predefinedSelected: Array<string> = [];
    let data: object = {
      'name': this.$props.field.name,
      'value': predefinedSelected
    };

    let updateState = this['updateState'];
    updateState(data);
  }
})

export default class CheckboxGroup extends Vue {
  updateStore(): void {
    let data: object = {
      'name': this.$props.field.name,
      'value': this['selected']
    };
    this.updateState(data);
  }

  updateState(data): void {
    this.$store.commit('SIMPLE_FIELD_UPDATE', data);
  }

  data(): object {
    let predefinedSelected: Array<string> = this.$props.field.selected || [];
    return {
      selected: []
    }
  }
  created(): void {
    console.log('created');
  }
  mounted(): void {
    console.log('mounted');
  }
  destroyed(): void {
    console.log('destroyed');
  }
}
</code>```

CheckboxGroup.vue

```<code>    <template>
  <div class="checkbox-group">
    <div class="row" v-if="field.label">
      <div class="col">
        {{field.label}}
      </div>
    </div>
    <div class="row">
      <div class="form-check col-3" v-for="option, key in field.options" :key="key">
        <label class="form-check-label">
          <input class="form-check-input" v-model="selected" @change="updateStore" type="checkbox" :name="field.name" :value="option.label"/>
          {{option.label}}
        </label>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import CheckboxGroup from './CheckboxGroup.ts'
  export default CheckboxGroup
</script>
</code>```

答:
The problem was solved easily. The problem was that I was changing the views based on an url, and rendering different components, but some of them were persistent in the view so Vue considered those are the same components that were needed in previous view. To solve this I just passed a key to the Page component, so in this situation it is treated as a different component and there is no shallow comparison inside the Page component.

Conclusion: Don't forget you keys guys and girls.

Body:
Vue.js version = 2.3.3

Question to everybody.
I have json which contains a list of data, based on the json I create form inputs. The form inputs have a model binded, which basically updates app state trough commits.

I have a component which renders a list of checkboxes,
On one page I have 1 instance and on the next one I have 3 instances of the component, each of them have their list of checkboxes, and a different name.

When going from page 1 to page 2, the checkbox_list component from page 1 doesn't fire the destroyed lifecycle hook (other components do fire this).

On page 2 I have 3 other components of type checkbox_list with their name, model and options. (data is initialized as a function).
Somehow the third component of type checkbox list doesn't fire the created hook, neither mounted or w/e. It is rendered but doesn't and events and the model is there, and from vue debugger the model array is empty.
The problem is that when I update checkbox model (by clicking on one of the checkboxes from the list) in the 3rd component instance (the one which didn't fire the created lifecycle hook) the model contains everything I've checked on the first page of the checkbox_list component instance.

The components are basically rendered in a loop as of the data is parsed.
Anybody any ideas why does this happen?
Thanks.

Please see bellow code of my components.
InputTypes.ts

import Vue from 'vue';
import Component from 'vue-class-component';

import TextInput from './text/TextInput.vue';
import EmailInput from './email/EmailInput.vue';
import RadioGroup from './radio/RadioGroup.vue';
import SelectInput from './select/SelectInput.vue';
import SelectAutocompleteInput from './select/SelectAutocompleteInput.vue';
import PasswordInput from './password/PasswordInput.vue';
import CheckboxGroup from './checkbox/CheckboxGroup.vue';
import AgreementSection from './custom/AgreementSection.vue';
import CvSection from './custom/CVSection.vue';
import SubmitSection from './custom/SubmitSection.vue';

@Component({
  name: 'input-types',
  props: ['field', 'lastPageIndex'],
  components: {
    TextInput,
    EmailInput,
    RadioGroup,
    SelectInput,
    SelectAutocompleteInput,
    PasswordInput,
    AgreementSection,
    CheckboxGroup,
    CvSection,
    SubmitSection
  },
  watch: {
    '$route'($to, $from) {
      let clearFields = this['clearFields'];
      clearFields();
    }
  }
})

export default class InputsTypes extends Vue {
  conditionalFields: object = {fields: []};

  clearFields(): void {
    this.$set(this.conditionalFields, 'fields', []);
  }

  changeHandler(fields): void {
    this.$set(this.conditionalFields, 'fields', fields);
  }

  updateModelValue(data): void {
    console.log(data);
  }
}

InputTypes.vue

<template>

    <text-input v-if="field.type == 'text'" :field="field"></text-input>

    <email-input v-else-if="field.type == 'email'" :field="field"></email-input>

    <checkbox-group v-else-if="field.type == 'checkbox_list'" :field="field"></checkbox-group>

    <radio-group v-else-if="field.type == 'radio'" :field="field" :onChange="changeHandler"></radio-group>

    <select-input  v-else-if="field.type == 'select'" :field="field" :onChange="changeHandler"></select-input>

    <select-autocomplete-input  v-else-if="field.type == 'select_autocomplete'" :field="field" :onChange="changeHandler"></select-autocomplete-input>

    <password-input v-else-if="field.type == 'password'" :field="field"></password-input>

    <agreement-section v-else-if="field.type == 'agreement'" :field="field"></agreement-section>

      {{field.label}}

        <input-types :field="option" :onChange="changeHandler"></input-types>

    <cv-section v-else-if="field.type == 'cv_section'" :field="field"></cv-section>
    <submit-section v-else-if="field.type == 'next_page'" :field="field" :lastPageIndex="lastPageIndex"></submit-section>

      <input-types :field="field" :onChange="changeHandler"></input-types>

</template>

CheckboxGroup.ts

import Vue from 'vue';
import Component from 'vue-class-component';

@Component({
  name: 'checkbox-group',
  props: ['field'],
  watch: {
    selected: (e) => {
      console.log(e);
    }
  },
  created(): void {
    let predefinedSelected: Array<string> = [];
    let data: object = {
      'name': this.$props.field.name,
      'value': predefinedSelected
    };

    let updateState = this['updateState'];
    updateState(data);
  }
})

export default class CheckboxGroup extends Vue {
  updateStore(): void {
    let data: object = {
      'name': this.$props.field.name,
      'value': this['selected']
    };
    this.updateState(data);
  }

  updateState(data): void {
    this.$store.commit('SIMPLE_FIELD_UPDATE', data);
  }

  data(): object {
    let predefinedSelected: Array<string> = this.$props.field.selected || [];
    return {
      selected: []
    }
  }
  created(): void {
    console.log('created');
  }
  mounted(): void {
    console.log('mounted');
  }
  destroyed(): void {
    console.log('destroyed');
  }
}

CheckboxGroup.vue

    <template>

        {{field.label}}

          <input class="form-check-input" v-model="selected" @change="updateStore" type="checkbox" :name="field.name" :value="option.label"/>
          {{option.label}}

</template>


来源: stackexchange

问:
google.maps.Polyline (JavaScript API) "path" property does not get initialized
I am receiving some sort of weird behavior from google.maps.Polyline class in JavaScript API of Google Maps.

What I am trying to achieve is simple - to draw a Polyline on a map from continuously updated Array of LatLngLiteral's.

The problem - the "path" property of google.maps.Polyline does not get initialized and therefore Polyline is not visible. The weird part is that regardless of the fact that I include "path" property in initialization of google.maps.Polyline, after the map is loaded, such property does not exist (although Polyline object is created and I can access other properties of it).

The precise error I get: "Cannot read property 'push' of undefined at ok (map.js:74)". I tried setting a value of "path" via setPath() method, I tried using LatLng classes, tried MVCArray class - nothing works. Thanks in advance for your assistance! The code is below. (the code below is not optimized, I'm just starting on basic functionality for this project)

```<code>function loadMap(){
    var options = {
        zoom : 15,
        center : {lat:42.553080288955805, lng: 11.25}
    };
    map = new google.maps.Map(document.getElementById("test-map"),options);
    player  = new google.maps.Marker(
            {
                map: map,
                position: {lat:42.553080288955805, lng: 11.25},
                title: "This is you!",
                label: {
                    text: "You are here!",
                    color: "rgb(50,50,255)",
                    fontFamily: "Helvetica, sans-serif",
                    fontWeight: "bold"
                }
            });

    //initializing path variable
    pathArray = [
        new google.maps.LatLng(-42, 11),
        new google.maps.LatLng(-43, 12),
        new google.maps.LatLng(-44, 15)
    ];
    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray, //the value here is not assigned for some reason
        strokeColor: "orange", //this property and value is assigned and
                               //accessible after the map was loaded
        visible: true
    });

}

let options2 = {
        enableHighAccuracy : true,
        timeout : 10000,
        maximumAge : 30000
    };

var positionWatcher = navigator.geolocation.watchPosition(ok,null,options2);
function ok(p){
    player.setPosition({lat:p.coords.latitude, lng:p.coords.longitude}); // works ok
    playerPath.path.push({lat:p.coords.latitude, lng:p.coords.longitude});
//above line provides the mentioned error
}
</code>```

答:
As there were no replies on this, I dug deep and found a working solution, however the question why "path" property of this object is not created during Polyline instance creation is still puzzling me.

In any case, it appears that "path" property only accepts google.maps.MVCArray([LatLng, LatLng]) as a value during the initialization. The JavaScript API says it should accept a regular Array object with either LatLng or LatLngLiteral as elements, but it doesn't (at least in my code, which is quite straightforward).

So if you have the same issue, I suggest initializing path like this:

```<code>pathArray = new google.maps.MVCArray([
        new google.maps.LatLng(-42, 11),
        new google.maps.LatLng(-43, 12),
        new google.maps.LatLng(-44, 15)
    ]);

    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am receiving some sort of weird behavior from google.maps.Polyline class in JavaScript API of Google Maps.

What I am trying to achieve is simple - to draw a Polyline on a map from continuously updated Array of LatLngLiteral's.

The problem - the "path" property of google.maps.Polyline does not get initialized and therefore Polyline is not visible. The weird part is that regardless of the fact that I include "path" property in initialization of google.maps.Polyline, after the map is loaded, such property does not exist (although Polyline object is created and I can access other properties of it).

The precise error I get: "Cannot read property 'push' of undefined at ok (map.js:74)". I tried setting a value of "path" via setPath() method, I tried using LatLng classes, tried MVCArray class - nothing works. Thanks in advance for your assistance! The code is below. (the code below is not optimized, I'm just starting on basic functionality for this project)

function loadMap(){
    var options = {
        zoom : 15,
        center : {lat:42.553080288955805, lng: 11.25}
    };
    map = new google.maps.Map(document.getElementById("test-map"),options);
    player  = new google.maps.Marker(
            {
                map: map,
                position: {lat:42.553080288955805, lng: 11.25},
                title: "This is you!",
                label: {
                    text: "You are here!",
                    color: "rgb(50,50,255)",
                    fontFamily: "Helvetica, sans-serif",
                    fontWeight: "bold"
                }
            });

    //initializing path variable
    pathArray = [
        new google.maps.LatLng(-42, 11),
        new google.maps.LatLng(-43, 12),
        new google.maps.LatLng(-44, 15)
    ];
    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray, //the value here is not assigned for some reason
        strokeColor: "orange", //this property and value is assigned and
                               //accessible after the map was loaded
        visible: true
    });

}

let options2 = {
        enableHighAccuracy : true,
        timeout : 10000,
        maximumAge : 30000
    };

var positionWatcher = navigator.geolocation.watchPosition(ok,null,options2);
function ok(p){
    player.setPosition({lat:p.coords.latitude, lng:p.coords.longitude}); // works ok
    playerPath.path.push({lat:p.coords.latitude, lng:p.coords.longitude});
//above line provides the mentioned error
}

Body:
As there were no replies on this, I dug deep and found a working solution, however the question why "path" property of this object is not created during Polyline instance creation is still puzzling me.

In any case, it appears that "path" property only accepts google.maps.MVCArray([LatLng, LatLng]) as a value during the initialization. The JavaScript API says it should accept a regular Array object with either LatLng or LatLngLiteral as elements, but it doesn't (at least in my code, which is quite straightforward).

So if you have the same issue, I suggest initializing path like this:

pathArray = new google.maps.MVCArray([
        new google.maps.LatLng(-42, 11),
        new google.maps.LatLng(-43, 12),
        new google.maps.LatLng(-44, 15)
    ]);

    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray
    });


问:
Handling async situations in an .NET MVC application
I wanted to get some basic .NET MVC understanding so I started working on a very simple application that is somewhat similar to Yelp.  It consists of a User object and Business object.  A user can add businesses to their "watch list" and when someone creates a review for that business the application would look through a table of "user id-business id" relations and email the users that are watching that business for new reviews (so that they can respond to them).

In my ReviewsController, I have a Create action that creates a review.  Before that action returns, I would like to run a method that checks if there are any watches for the business the review was just created for.

This is where I get stuck because I'm not sure what would be a good way of doing this in MVC setting(?).

What I do know is that the user who is creating the review does not need to wait for the application to look through the "user-business" relation table.

Would it be a good idea to create this lookup functionality as an async method? I also looked into events but seems like events are not ideal in MVC setting. Are there any well-established patters in MVC world for situations like these?

答:
You can use the Task Parallel Library to create asyncronous tasks. The following code executes the CreateReview method, when it finishes creates a thread and executes the method CheckWatches. At the same time it returns the action Create whitout waiting the new thread finishes.

```<code>public ActionResult Create()
{
     // User related task
     CreateReview();
     Task.Factory.StartNew(() =>
      {
               // system related task
             CheckWatches();
      });

    return View();
}
</code>```

Body:
You can use the Task Parallel Library to create asyncronous tasks. The following code executes the CreateReview method, when it finishes creates a thread and executes the method CheckWatches. At the same time it returns the action Create whitout waiting the new thread finishes.

public ActionResult Create()
{
     // User related task
     CreateReview();
     Task.Factory.StartNew(() =>
      {
               // system related task
             CheckWatches();
      });

    return View();
}


问:
Generating types from schema for TypeScript yields empty file
I take these steps, which means, I first create the json:

```<code>apollo-codegen introspect-schema schema.graphqls --output schema.json
</code>```

which yields:

```<code>{
  "data": {
    "__schema": {
      "queryType": {
        "name": "Query"
      },
      "mutationType": null,
      "subscriptionType": null,
      "types": [
        {
          "kind": "OBJECT",
          "name": "Query",
          "description": "",
          "fields": [
            {

              ...
</code>```

But after, when I run:

```<code> apollo-codegen generate **/*.graphqls --schema schema.json --target typescript --output schema.ts
</code>```

I get an empty schema.ts types file:

```<code>/* tslint:disable */
//  This file was automatically generated and should not be edited.
/* tslint:enable */
</code>```

Ideas?

答:
In your apollo-codegen generate line you're targeting .graphl*s* files. Should that be .graphql?

Which file(s) are you expecting the generator to match? It needs to have files that contain queries or mutations that would be run against your schema - it won't generate code for the schema itself:

The purpose of this command is to generate types for query and mutation operations made against the schema (it will not generate types for the schema itself).

Source: https://www.apollographql.com/docs/angular/features/developer-tooling.html#introspect

Body:
I take these steps, which means, I first create the json:

apollo-codegen introspect-schema schema.graphqls --output schema.json

which yields:

{
  "data": {
    "__schema": {
      "queryType": {
        "name": "Query"
      },
      "mutationType": null,
      "subscriptionType": null,
      "types": [
        {
          "kind": "OBJECT",
          "name": "Query",
          "description": "",
          "fields": [
            {

              ...

But after, when I run:

 apollo-codegen generate **/*.graphqls --schema schema.json --target typescript --output schema.ts

I get an empty schema.ts types file:

/* tslint:disable */
//  This file was automatically generated and should not be edited.
/* tslint:enable */

Ideas?


问:
How to properly mock and unit test
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

```<code>    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }
</code>```

答:
Essentially what you are testing here is that the methods are getting called, not whether or not they actually work.  Which is what mocks are supposed to do.  Instead of calling the method, they just check to see if the method got called, and return whatever is in the Return() statement. So in your assertion here:

```<code>Assert.That(result, Is.False, "error message here");
</code>```

This assertion will ALWAYS succeed because your expectation will ALWAYS return false, because of the Return statement:

```<code>userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
</code>```

I'm guessing this isn't that useful in this case.

Where mocking is useful is when you want to, for example, make a database call somewhere in your code, but you don't want to actually call to the database.  You want to pretend that the database got called, but you want to set up some fake data for it to return, and then (here's the important part) test the logic that does something with the fake data your mock returned.  In the above examples you are omitting the last step. Imagine you had a method that displayed a message to the user that said whether the new user was created:

```<code>public string displayMessage(bool userWasCreated) {
    if (userWasCreated)
        return "User created successfully!";
    return "User already exists";
}
</code>```

then your test would be

```<code>userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
Assert.AreEqual("User already exists", displayMessage(userSvc.CreateUser(theUser)))
</code>```

Now this has some value, because you are testing some actual behavior.  Of course, you could also just test this directly by passing in "true" or "false."  You don't even need a mock for that test.  Testing expectations is fine, but I've written plenty of tests like that, and have come to the same conclusion that you are reaching - it just isn't that useful.

So in short, mocking is useful when you want to abstract away externalities, like databases, or webservice calls, etc, and inject known values at that point.  But it's not often useful to test mocks directly.

OwnerDisplayName: Ben Robbins

ContentLicense: CC BY-SA 2.5

Title: How to properly mock and unit test

Body:
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }

Body:
Essentially what you are testing here is that the methods are getting called, not whether or not they actually work.  Which is what mocks are supposed to do.  Instead of calling the method, they just check to see if the method got called, and return whatever is in the Return() statement. So in your assertion here:

Assert.That(result, Is.False, "error message here");

This assertion will ALWAYS succeed because your expectation will ALWAYS return false, because of the Return statement:

userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);

I'm guessing this isn't that useful in this case.

Where mocking is useful is when you want to, for example, make a database call somewhere in your code, but you don't want to actually call to the database.  You want to pretend that the database got called, but you want to set up some fake data for it to return, and then (here's the important part) test the logic that does something with the fake data your mock returned.  In the above examples you are omitting the last step. Imagine you had a method that displayed a message to the user that said whether the new user was created:

public string displayMessage(bool userWasCreated) {
    if (userWasCreated)
        return "User created successfully!";
    return "User already exists";
}

then your test would be

userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
Assert.AreEqual("User already exists", displayMessage(userSvc.CreateUser(theUser)))

Now this has some value, because you are testing some actual behavior.  Of course, you could also just test this directly by passing in "true" or "false."  You don't even need a mock for that test.  Testing expectations is fine, but I've written plenty of tests like that, and have come to the same conclusion that you are reaching - it just isn't that useful.

So in short, mocking is useful when you want to abstract away externalities, like databases, or webservice calls, etc, and inject known values at that point.  But it's not often useful to test mocks directly.

OwnerDisplayName: Doug R


问:
d3 topojson wont generate state outlines
I am trying to generate outlines of states like in this tutorial http://duspviz.mit.edu/d3-workshop/mapping-data-with-d3/ towards the bottom. I've gotten everything else except for the states outlines.

```<code>var width2 = 720;
        var height2 = 500;

        var projection = d3.geoAlbers()
            .scale(1000)
            .translate([width2/2, height2/2]);

        var path = d3.geoPath()
            .projection(projection);

        var path2 = d3.geoPath()
            .projection(null);

        var svg = d3.select("#map2").append("svg")
            .attr("width", width2)
            .attr("height", height2);

        d3.queue()
            .defer(d3.json, "../data/us.json")
            .defer(d3.tsv, '../data/us_unemployment_2008.tsv')
            .await(ready);  //run ready when jsons are loaded

        function ready(error, us, us_unemployment_2008){
            if (error) throw error;

            var ratebyid = {};
            us_unemployment_2008.forEach(function(d){
                ratebyid[d.id] = +d.rate;
            });

            svg.append('g')
                .attr('class','counties')
                .selectAll('path')
                .data(topojson.feature(us, us.objects.counties).features)
                .enter().append('path')
                .attr('d', path)
                .style('fill','white')
                .style('stroke','black');

            var color = d3.scaleThreshold()
                .domain([0.02, 0.04, 0.06, 0.08, 0.10])
                .range(["#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f"]);

            svg.append('g')
                .attr('class','counties')
                .selectAll('path')
                .data(topojson.feature(us, us.objects.counties).features)
                .enter().append('path')
                .attr('d', path)
                .style('fill', function(d){
                    return color(ratebyid[d.id]);
                });

            svg.append("path")
                .datum(topojson.mesh(us, us.objects.states, function(a, b) {
                    return a.id !== b.id;
                }))
                .attr("class", "states")
                // .attr('fill','none')
                .attr("d", path);
        }
</code>```

The fragmentation looks like this:

I was able to fix this by adding .attr('fill', 'none') to the svg path. But now it does not show the white outline of the states like in the tutorial.

Now it looks like this:

This is what I want it to look like:

答: Adding <code>.attr("stroke","white")</code> did the trick. I thought I had tried this. From what I understand, this should not be necessary because the tutorial did not include this, but it works. </p>

Body:
I am trying to generate outlines of states like in this tutorial http://duspviz.mit.edu/d3-workshop/mapping-data-with-d3/ towards the bottom. I've gotten everything else except for the states outlines.

var width2 = 720;
        var height2 = 500;

        var projection = d3.geoAlbers()
            .scale(1000)
            .translate([width2/2, height2/2]);

        var path = d3.geoPath()
            .projection(projection);

        var path2 = d3.geoPath()
            .projection(null);

        var svg = d3.select("#map2").append("svg")
            .attr("width", width2)
            .attr("height", height2);

        d3.queue()
            .defer(d3.json, "../data/us.json")
            .defer(d3.tsv, '../data/us_unemployment_2008.tsv')
            .await(ready);  //run ready when jsons are loaded

        function ready(error, us, us_unemployment_2008){
            if (error) throw error;

            var ratebyid = {};
            us_unemployment_2008.forEach(function(d){
                ratebyid[d.id] = +d.rate;
            });

            svg.append('g')
                .attr('class','counties')
                .selectAll('path')
                .data(topojson.feature(us, us.objects.counties).features)
                .enter().append('path')
                .attr('d', path)
                .style('fill','white')
                .style('stroke','black');

            var color = d3.scaleThreshold()
                .domain([0.02, 0.04, 0.06, 0.08, 0.10])
                .range(["#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f"]);

            svg.append('g')
                .attr('class','counties')
                .selectAll('path')
                .data(topojson.feature(us, us.objects.counties).features)
                .enter().append('path')
                .attr('d', path)
                .style('fill', function(d){
                    return color(ratebyid[d.id]);
                });

            svg.append("path")
                .datum(topojson.mesh(us, us.objects.states, function(a, b) {
                    return a.id !== b.id;
                }))
                .attr("class", "states")
                // .attr('fill','none')
                .attr("d", path);
        }

The fragmentation looks like this:

I was able to fix this by adding .attr('fill', 'none') to the svg path. But now it does not show the white outline of the states like in the tutorial.

Now it looks like this:

This is what I want it to look like:

Body: Adding .attr("stroke","white") did the trick. I thought I had tried this. From what I understand, this should not be necessary because the tutorial did not include this, but it works.


问:
On Hybrid Runbook Worker suddenly all jobs are getting suspended
I have an automation account configured with a Hybrid Runbook Worker, suddenly all jobs are getting suspended with the error:

Job was suspended. For additional troubleshooting, check the Microsoft-SMA event logs on the computers in the Hybrid Runbook Worker Group that tried to run this job.

Any idea? what can be the issue

答: This has been fixed, it was a brief issue with the service.</p>


问:
Sharing cookies across domains and subdomains
I'm trying to implement a multi-tenancy architecture with Django and django-tenant-schemas.

I'm successfully accessing the baseapp from http://app.mysite.com:8000/ and setting a cookie sessionId (which is http-only) when I log into the application. (Port 8000 is only for development)

I'm now trying to make a request to http://tenant1.mysite.com:8000/accounting/. When I inspect the request headers, however, I see that the cookies have not been set even though in my settings file I have:

```<code>SESSION_COOKIE_DOMAIN = ".mysite.com"
CSRF_COOKIE_DOMAIN = ".mysite.com"
</code>```

I was under the impression that setting my cookie domain to .mysite.com would allow access to subdomains. What am I missing here?

答:
I know this is a bit old, but just in case someone lands here wondering about a similar issue it is possible that the cookie is set but the SessionMiddleware does not find a valid session for the session id received. This could happen for example if you are using the database session backend and you happen to have put django.contrib.sessions in your TENANT_APPS list. In this case Django won't find any session because when you logged in at app.mysite.com the session was stored in the database schema corresponding to the app tenant and when you tried to access tenant1.mysite.com the SessionMiddleware looked for a session stored in the tenant1 schema.

So the conclusion to this is, if you are using the database backend for storing sessions, then you should put django.contrib.sessions into your SHARED_APPS list and not into TENANT_APPS list.

Hope this helps.

Body:
I'm trying to implement a multi-tenancy architecture with Django and django-tenant-schemas.

I'm successfully accessing the baseapp from http://app.mysite.com:8000/ and setting a cookie sessionId (which is http-only) when I log into the application. (Port 8000 is only for development)

I'm now trying to make a request to http://tenant1.mysite.com:8000/accounting/. When I inspect the request headers, however, I see that the cookies have not been set even though in my settings file I have:

SESSION_COOKIE_DOMAIN = ".mysite.com"
CSRF_COOKIE_DOMAIN = ".mysite.com"

I was under the impression that setting my cookie domain to .mysite.com would allow access to subdomains. What am I missing here?


问:
Discriminant Solutions Calculation Batch File (Square Root)
New here but I will try to be short and on the point. I am trying to create a program that has the user input 3 values which the program then proceeds and uses as the A, B and C respectively in the ax^2+bx+c (discriminant = D) and gives you the "solutions" it has (if D>0 then 2 solutions, if D = 0 one "double" solution and if D < 0 it will display that there are no real solutions) . Thing is, no matter how hard i have tried, I cannot come up with a way to calculate the square root later in the process (should the discriminant be positive). I have tried instead of trying to find the square root to raise the discriminant to 1/2 (i.e. D^(1/2)) and no results, maybe i am doing it wrong though

```<code>:positive
:squareroot
set /p M==%B%*%B%-4*%A%*%C%
set /a number=%M%, last=2, sqrt=number/last
:next
set /a last=(last+sqrt)/2, sqrt=number/last
if %sqrt% lss %last% goto next
set /a Q=(-%B%+%last%)/2*%A%
set /a R=(-%B%-%last%)/2*%A%
echo ----------------------------------------------------
echo The first solution is ~%Q%~ and the second is ~%R%~ !
echo ----------------------------------------------------
pause
goto start
</code>```

After trying and searching on the web, i found the above code which actually somehow manages to calculate the square root of a number, at close approximation (i.e. square root of 9 = 3 BUT square root of 15 also = 3). Nonetheless for the purposes of the project it suits my needs.

Instead of calculating the number the program displays %B%*%B%-4*%A%*%C% (instead of the variables, the values the user chose) and then shuts down.

答:
well, I'll try to guess, what you try to do. (expanded the example with some variables that obviously got defined somewhere else in your code to make it work).

Your line set /p M==%B%*%B%-4*%A%*%C% is nonsense. set /p asks the user for input, so you don't want to use /p. Variables are set with a simple =, not == and I think you want the variable to hold the formula, not the result. %B% is replaced by the value of the variable B, probably not, what you want. To escape the percent signs, double them, so the %M% would literally contain %B%*%B%-4*%A%*%C%.

Just set /a number=%M% would not work, because you want the variables to be evaluated here, so you need another layer of parsing (you can do it with call).

```<code>@echo off
setlocal
:positive
:squareroot
set b=3
set a=4
set c=5

set  "M=%%B%%*%%B%%-4*%%A%%*%%C%%"
call set /a number=%M%
set /a last=2, sqrt=number/last

:next
set /a last=(last+sqrt)/2, sqrt=number/last
if %sqrt% lss %last% goto next
set /a Q=(-%B%+%last%)/2*%A%
set /a R=(-%B%-%last%)/2*%A%
echo ----------------------------------------------------
echo The first solution is ~%Q%~ and the second is ~%R%~ !
echo ----------------------------------------------------
pause
goto start
</code>```

(Note: I didn't analyze the rest of the code, as it seems to work fine)

Body:
New here but I will try to be short and on the point. I am trying to create a program that has the user input 3 values which the program then proceeds and uses as the A, B and C respectively in the ax^2+bx+c (discriminant = D) and gives you the "solutions" it has (if D>0 then 2 solutions, if D = 0 one "double" solution and if D < 0 it will display that there are no real solutions) . Thing is, no matter how hard i have tried, I cannot come up with a way to calculate the square root later in the process (should the discriminant be positive). I have tried instead of trying to find the square root to raise the discriminant to 1/2 (i.e. D^(1/2)) and no results, maybe i am doing it wrong though

:positive
:squareroot
set /p M==%B%*%B%-4*%A%*%C%
set /a number=%M%, last=2, sqrt=number/last
:next
set /a last=(last+sqrt)/2, sqrt=number/last
if %sqrt% lss %last% goto next
set /a Q=(-%B%+%last%)/2*%A%
set /a R=(-%B%-%last%)/2*%A%
echo ----------------------------------------------------
echo The first solution is ~%Q%~ and the second is ~%R%~ !
echo ----------------------------------------------------
pause
goto start

After trying and searching on the web, i found the above code which actually somehow manages to calculate the square root of a number, at close approximation (i.e. square root of 9 = 3 BUT square root of 15 also = 3). Nonetheless for the purposes of the project it suits my needs.

Instead of calculating the number the program displays %B%*%B%-4*%A%*%C% (instead of the variables, the values the user chose) and then shuts down.

Body:
well, I'll try to guess, what you try to do. (expanded the example with some variables that obviously got defined somewhere else in your code to make it work).

Your line set /p M==%B%*%B%-4*%A%*%C% is nonsense. set /p asks the user for input, so you don't want to use /p. Variables are set with a simple =, not == and I think you want the variable to hold the formula, not the result. %B% is replaced by the value of the variable B, probably not, what you want. To escape the percent signs, double them, so the %M% would literally contain %B%*%B%-4*%A%*%C%.

Just set /a number=%M% would not work, because you want the variables to be evaluated here, so you need another layer of parsing (you can do it with call).

@echo off
setlocal
:positive
:squareroot
set b=3
set a=4
set c=5

set  "M=%%B%%*%%B%%-4*%%A%%*%%C%%"
call set /a number=%M%
set /a last=2, sqrt=number/last

:next
set /a last=(last+sqrt)/2, sqrt=number/last
if %sqrt% lss %last% goto next
set /a Q=(-%B%+%last%)/2*%A%
set /a R=(-%B%-%last%)/2*%A%
echo ----------------------------------------------------
echo The first solution is ~%Q%~ and the second is ~%R%~ !
echo ----------------------------------------------------
pause
goto start

(Note: I didn't analyze the rest of the code, as it seems to work fine)


问:
updating specific cell csv file using java
Hi i have a small problem and think i'm just not getting the correct syntax on one line of code. basically, i can write into my csv file and find a specific record using string tokenizer but it is not updating/editing the specified cells of that record. the record remains the same. please help....</p>

答:
I used the below code where I will replace a string with another and it worked exactly the way I needed:</p>

```<code>public static void updateCSV(String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);

        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
        List<String[]> csvBody = reader.readAll();
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
                if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
                    csvBody.get(i)[j] = "Updated_date"; //Target replacement
                }
            }
        }
        reader.close();

        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }
</code>```

Body:
I used the below code where I will replace a string with another and it worked exactly the way I needed:

public static void updateCSV(String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);

        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
        List<String[]> csvBody = reader.readAll();
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
                if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
                    csvBody.get(i)[j] = "Updated_date"; //Target replacement
                }
            }
        }
        reader.close();

        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }


问:
Application status monitoring in websphere
is there a way to interact with websphere 6.1 from a servlet to check if an application is running ? If so, is such transaction too resource-consuming operation to do it let's say before an "index" page is loaded ?.

The java.net.URL approach is simpler but discarded.

Thanks

答: you can use the mbean/jmx interface: search for this infocenter topic in your release: tjmx_updating_app.html </p>


问:
Cannot start docker after installation on Windows 10 Home edition
I am brand new to docker with windows. I have installed the Docker toolbox version as my laptop cannot run hyper-v. After the installation of Docker Toolbox (OS is Windows 10 Home) I run Docker Quickstart Terminal and in the console, I see this:

Running pre-create checks...
  Error with pre-create check: "This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory"
  Looks like something went wrong in step ´Checking if machine default exists´... Press any key to continue...

I have opened my BIOS menu to try to change this but I am not presented with an option to do so as if it's hidden. I've no idea how to get around this and other StackOverflow solutions are not fixing my issue.

My Laptop model is an Acer Aspire E1-531.

Any help on enabling the VT-X/AMD-v would be brilliant thanks

答: Follow this link to see your laptop support VT-X/AMD-v. If not then you have no other choice other than changing your laptop to run hypervisors.</p>


问:
Firebase Cloud Trigger Function - How can I send notifications to ALL users?
I am totally new to Firebase Cloud Functions (2 days exposure). I am trying to send notifications to ALL users of my app when Firebase Database detects that new data has been added. Here is what I have so far:

```<code>exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {

  const snapshot = event.data;
  var str = snapshot.child("name").val();
  console.log(str);

  if (snapshot.previous.val()) {
    return 0;
  }

  if (snapshot.val().name != "ADMIN") {
    return 0;
  }

  const text = snapshot.val().text;
  const payload = {
    notification: {
      title: snapshot.name,
      body: ""
    }
  }
  //return admin.messaging().sendToDevice(tokens, payload);
});
</code>```

I know the code is in a state of mess right now, its due to a couple of copy and testing from various tutorial sites. I can succesfully get the data's name from console.log but am unable to send notification to ALL users.

I am aware that most use tokens and device IDs. But is there any easier way to send to each and every one of my users ? And do I need to add any java codes for my app for this notification to work ?

EDIT 1:
Following Peter's suggestions, I have updated my functions:

```<code>exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {

  const snapshot = event.data;
  var str = snapshot.child("name").val();
  console.log(str);

  if (snapshot.previous.val()) {
    console.log("RETURN 1");
    return 0;
  }

  const payload = {
    notification: {
      title: str,
      body: ""
    }
  }

  return admin.messaging().sendToTopic("Users", payload)
  .then(function(response){
        console.log("Notification sent ", response);
  })
  .catch(function(error){
        console.log("Error sending notification: ", error);
  });
});
</code>```

I have also added the following java to my code:

```<code>FirebaseMessaging.getInstance().subscribeToTopic("Users");
</code>```

Problem I am having now is that on the Firebase console it says that the notification is being sent successfully, but on my phone I am not receiving anything. Is it a must to use the onMessageReceived method in my case ?

One thing I noticed is that the above statement is being called each time the app launches. Will this effect the result in any way ?

答:
I think the easiest one is topics, you can subscribe all the users to a single topic and then send a notification to that topic. You have to change your return statement to this:

```<code>return admin.messaging().sendToTopic("Cat", payload);
</code>```

So now all the users subscribed to the topic "Cat" will receive the notification. Of course you can change the topic also to anything you want..

To subscribe users to a topic, all you need to do is write this:

```<code>FirebaseMessaging.getInstance().subscribeToTopic("Cat"); //in java code
</code>```

check this for more info topic messaging

Body:
I am totally new to Firebase Cloud Functions (2 days exposure). I am trying to send notifications to ALL users of my app when Firebase Database detects that new data has been added. Here is what I have so far:

exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {

  const snapshot = event.data;
  var str = snapshot.child("name").val();
  console.log(str);

  if (snapshot.previous.val()) {
    return 0;
  }

  if (snapshot.val().name != "ADMIN") {
    return 0;
  }

  const text = snapshot.val().text;
  const payload = {
    notification: {
      title: snapshot.name,
      body: ""
    }
  }
  //return admin.messaging().sendToDevice(tokens, payload);
});

I know the code is in a state of mess right now, its due to a couple of copy and testing from various tutorial sites. I can succesfully get the data's name from console.log but am unable to send notification to ALL users.

I am aware that most use tokens and device IDs. But is there any easier way to send to each and every one of my users ? And do I need to add any java codes for my app for this notification to work ?

EDIT 1:
Following Peter's suggestions, I have updated my functions:

exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {

  const snapshot = event.data;
  var str = snapshot.child("name").val();
  console.log(str);

  if (snapshot.previous.val()) {
    console.log("RETURN 1");
    return 0;
  }

  const payload = {
    notification: {
      title: str,
      body: ""
    }
  }

  return admin.messaging().sendToTopic("Users", payload)
  .then(function(response){
        console.log("Notification sent ", response);
  })
  .catch(function(error){
        console.log("Error sending notification: ", error);
  });
});

I have also added the following java to my code:

FirebaseMessaging.getInstance().subscribeToTopic("Users");

Problem I am having now is that on the Firebase console it says that the notification is being sent successfully, but on my phone I am not receiving anything. Is it a must to use the onMessageReceived method in my case ?

One thing I noticed is that the above statement is being called each time the app launches. Will this effect the result in any way ?

Body:
I think the easiest one is topics, you can subscribe all the users to a single topic and then send a notification to that topic. You have to change your return statement to this:

return admin.messaging().sendToTopic("Cat", payload);

So now all the users subscribed to the topic "Cat" will receive the notification. Of course you can change the topic also to anything you want..

To subscribe users to a topic, all you need to do is write this:

FirebaseMessaging.getInstance().subscribeToTopic("Cat"); //in java code

check this for more info topic messaging


问:
OCIEnvCreate failed with return code 1 but error message text was not available
I'm having some trouble with this exception.
I already tried this options that i saw here.

The causes:
You are using an unsupported version of the Oracle Client (older than 11.2) on Windows 7.
DLLs from a previous installation of Oracle Client have been left on the system, causing a conflict.
The solutions:
Install a supported version of the Oracle Client.
Perform a search for "OCI.DLL" on the local machine. If you find any instances of this file in any location other than your ORACLE_HOME rename or delete it. If in doubt, uninstall the Oracle Client, then perform the search again. Anything that is leftover is the culprit.

**And I gave permission to all of the Oracle paths. I'm looking for some other solution or help.

答:
I had a similar problem and solved it by editing the .csproj file. In my case, I was using a project to connect to the database and in another application, a console application, I was doing the logic of my program and calling that library. To solve the problem I've checked the section of my .csproj. In the database connection project the "Debug | Any CPU" property was different in comparisson with my console application .csproj. I've replaced it by this:</p>

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
</code>```

Body:
I had a similar problem and solved it by editing the .csproj file. In my case, I was using a project to connect to the database and in another application, a console application, I was doing the logic of my program and calling that library. To solve the problem I've checked the section of my .csproj. In the database connection project the "Debug | Any CPU" property was different in comparisson with my console application .csproj. I've replaced it by this:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>


问:
Subselect in the ON clause
Please dont bash me if there are already answers for this question, but I found none.

Basically I want to make a subselect in the ON clause of a Left join to get the newest entry in a timeframe.

(start and endtime are timestamps, hardcoded, in local variables or host variables in a Cobol program) to simplify I used integers in that question.

```<code>Select * from table1 as t1
left join table2 as t2 on
t1.primary = t2.secondary
and t2.timestamp = (
    select max(t2a.timestamp) from table2 as t2a
        where t2.primary = t2a.primary
            and t2a.timestamp > starttime
            and t2a.timestamp < endtime
    )
</code>```

Now this does not work, I get the following error:

AN ON CLAUSE IS INVALID. SQLCODE=-338

Because (see the docs)

The ON clause cannot contain a subquery.

Now what we can do to surround that is instead of joining table2 to join a already delimited subquery. But that surrounds the query optimizer what literally kills the performance:

```<code>Select * from table1 as t1
left join (
    select t2a.secondary from table2 as t2a
        where t2a.timestamp = (
            select max(t2b.timestamp)
            from table2 as t2b
            where t2a.primary = t2b.primary
            and t2b.timestamp > starttime
            and t2b.timestamp < endtime
        )
    )as t2
on t1.primary = t2.secondary
</code>```

Any idea how to slove this?

Example data table1:

```<code>t1.primary
         1
         2
         3
</code>```

Example data table2:

```<code>t2.primary t2.secondary t2.timestamp
         1            1           4
         2            1           5
         3            1          10
         4            2           4
         5            2           5
</code>```

Variables:

```<code>starttime = 3
endtime   = 6
</code>```

Expected result:

```<code>t1.primary t2.primary t2.secondary t2.timestamp
         1          2            1           5  --Leftjoined the newest entry in range
         2          5            2           5
         3       NULL         NULL        NULL
</code>```

答:
something like this.  Just typed in before lunch so don't bash me if it doesn't work.

```<code>select * from table1 a left join
(select t2b.primary, max(t2b.timestamp) mxts
            from table2 t2b
            group by t2b.primary
) as b on a.primary = b.primary
left join table2 on b.primary = table2.secondary and
table2.timestamp = mxts and table2.timestamp between mystartts and myendts
</code>```

NOte: Don't assume timestamps are unique and can be used to extract the last entry from a table because this will undobtly fraile.

Title: Subselect in the ON clause

Body:
Please dont bash me if there are already answers for this question, but I found none.

Basically I want to make a subselect in the ON clause of a Left join to get the newest entry in a timeframe.

(start and endtime are timestamps, hardcoded, in local variables or host variables in a Cobol program) to simplify I used integers in that question.

Select * from table1 as t1
left join table2 as t2 on
t1.primary = t2.secondary
and t2.timestamp = (
    select max(t2a.timestamp) from table2 as t2a
        where t2.primary = t2a.primary
            and t2a.timestamp > starttime
            and t2a.timestamp < endtime
    )

Now this does not work, I get the following error:

AN ON CLAUSE IS INVALID. SQLCODE=-338

Because (see the docs)

The ON clause cannot contain a subquery.

Now what we can do to surround that is instead of joining table2 to join a already delimited subquery. But that surrounds the query optimizer what literally kills the performance:

Select * from table1 as t1
left join (
    select t2a.secondary from table2 as t2a
        where t2a.timestamp = (
            select max(t2b.timestamp)
            from table2 as t2b
            where t2a.primary = t2b.primary
            and t2b.timestamp > starttime
            and t2b.timestamp < endtime
        )
    )as t2
on t1.primary = t2.secondary

Any idea how to slove this?

Example data table1:

t1.primary
         1
         2
         3

Example data table2:

t2.primary t2.secondary t2.timestamp
         1            1           4
         2            1           5
         3            1          10
         4            2           4
         5            2           5

Variables:

starttime = 3
endtime   = 6

Expected result:

t1.primary t2.primary t2.secondary t2.timestamp
         1          2            1           5  --Leftjoined the newest entry in range
         2          5            2           5
         3       NULL         NULL        NULL

Body:
something like this.  Just typed in before lunch so don't bash me if it doesn't work.

select * from table1 a left join
(select t2b.primary, max(t2b.timestamp) mxts
            from table2 t2b
            group by t2b.primary
) as b on a.primary = b.primary
left join table2 on b.primary = table2.secondary and
table2.timestamp = mxts and table2.timestamp between mystartts and myendts

NOte: Don't assume timestamps are unique and can be used to extract the last entry from a table because this will undobtly fraile.


问:
iphone toRadians toDegrees compiler problem
I am trying to convert a double to radians using the Objective c function toRadians like this:

```<code>double oldLat = toRadians(oldLocation.coordinate.latitude);
</code>```

but I keep getting a compiler warning and error or implicit declaration of toRadians and toDegrees

I included #import <math.h> but that didn't solve the problem for some reason.

any help would be greatly appreciated.

答:
There is no toRadians in the Foundation classes.  You can just convert it manually

degrees * M_PI / 180.0

Foundation imports math.h so you'll have M_PI otherwise you'll have to

#include <math.h>

Body:
I am trying to convert a double to radians using the Objective c function toRadians like this:

double oldLat = toRadians(oldLocation.coordinate.latitude);

but I keep getting a compiler warning and error or implicit declaration of toRadians and toDegrees

I included #import <math.h> but that didn't solve the problem for some reason.

any help would be greatly appreciated.


问:
How add a a field obtained in a form to a table in access? How can I use VBA?
I am working on an access database and have several fields on a table and the same fields plus another calculated field, resulting from a calculation of different field values, in a form. I want to be able to export this new field from the form into a field in the table. How can I do that? Do I really need to use Visual Basic access?</p>

答:
Thanks everybody for helping me. I changed the whole database and arranged the formulas into queries and worked for me.
Thanks from a real newbie</p>


问:
wait.until(ExpectedConditions.visibilityOf(userName)) is not working
In the below code on 33rd line getting below error message near wait.until

Multiple markers at this line
    - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
    - The method until(Function) in the type FluentWait is not applicable for the
     arguments (ExpectedCondition)

```<code>   package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

 package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
</code>```

答:
Play with conditions with By/WebElement:</p>

```<code>ExpectedConditions.presenceOfAllElementsLocatedBy(By)
ExpectedConditions.elementExists(By)
ExpectedConditions.elementIsVisible(By)
ExpectedConditions.elementToBeClickable(By/WebElement)
ExpectedConditions.visibilityOfAllElementsLocatedBy(By)
</code>```

Body:
In the below code on 33rd line getting below error message near wait.until

Multiple markers at this line
    - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
    - The method until(Function) in the type FluentWait is not applicable for the
     arguments (ExpectedCondition)

   package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

 package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

Body:
Play with conditions with By/WebElement:

ExpectedConditions.presenceOfAllElementsLocatedBy(By)
ExpectedConditions.elementExists(By)
ExpectedConditions.elementIsVisible(By)
ExpectedConditions.elementToBeClickable(By/WebElement)
ExpectedConditions.visibilityOfAllElementsLocatedBy(By)


问:
ParseExection error in Hive
I am getting an error when executing a select statement in Hive.

Error: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 1:33 cannot recognize input near '' '' ''

Query Sample: ;with cte1 as ( select * from table1)
, cte2 as ( select * from table2)
, cte3 as (select * from table3)
select * from cte2
join cte3 on cte2.col1 = cte3.col1
join cte1 on cte1.col1 = cte2.col1;

答:
you are missing the alias reference, add the keywound "as" after your alias like

```<code>with cte1 as  ( select * from table1) , cte2 as ( select * from table2) , cte3 as ( select * from table3) select * from cte2 join cte3 on cte2.col1 = cte3.col1 join cte1 on cte1.col1 = cte2.col1
</code>```

Tested in hive 1.1

Title: ParseExection error in Hive

Body:
you are missing the alias reference, add the keywound "as" after your alias like

with cte1 as  ( select * from table1) , cte2 as ( select * from table2) , cte3 as ( select * from table3) select * from cte2 join cte3 on cte2.col1 = cte3.col1 join cte1 on cte1.col1 = cte2.col1

Tested in hive 1.1


问:
How to create a pojo from xml for jaxb ( Unmarshalling)
```<code><?xml version="1.0" encoding="UTF-8"?>

<STATUS_UPDATE>
    <UPDATES_COUNTER>2</UPDATES_COUNTER>
    <LETTERS>
        <LETTER>
            <LETTER_KEY>key1</LETTER_KEY>
            <STATUS>status1</STATUS>
        </LETTER>
        <LETTER>
            <LETTER_KEY>key2</LETTER_KEY>
            <STATUS>status2</STATUS>
        </LETTER>
    </LETTERS>
</STATUS_UPDATE>
</code>```

So i have this xml. Im trying to create a pojo from it.

```<code>@XmlRootElement(name = "STATUS_UPDATE")
public class StatusUpdate {

    private int updatesCounter;

    List<Letter> letters;

    public StatusUpdate(){
        letters = new ArrayList<Letter>();
    }

    public StatusUpdate(int updatesCounter, List<Letter> letters){
        super();
        this.updatesCounter = updatesCounter;
        this.letters =  letters;
    }

    @XmlElement(name="LETTERS")
    public List<Letter> getLetters() {
        return letters;
    }

    public void setLetters(List<Letter> letters) {
        this.letters = letters;
    }
    @XmlElement(name="UPDATES_COUNTER")
    public int getUpdatesCounter() {
        return updatesCounter;
    }

    public void setUpdatesCounter(int updatesCounter) {
        this.updatesCounter = updatesCounter;
    }

}
</code>```

And letter class

```<code>@XmlRootElement(name = "LETTER")
public class Letter {

    public Letter(){

    }

    public Letter(String letterKey,String status){
        this.letterKey = letterKey;
        this.status = status;
    }
    String letterKey;
    String status;

    @XmlElement(name="LETTER_KEY")
    public String getLetterKey() {
        return letterKey;
    }
    public void setLetterKey(String letterKey) {
        this.letterKey = letterKey;
    }
    @XmlElement(name="STATUS")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}
</code>```

and this code snipper wont seem to do the job.
i get no errors, code runs, i get a 2 in my updateCounter variable,
but my list is empty with only one letter object, with both variables null.

```<code>File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(StatusUpdate.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StatusUpdate msgObject = (StatusUpdate) jaxbUnmarshaller.unmarshal(file);
</code>```

I've been reading the documentations and examples, but most of them are either written to match variable names and xml elemenets (which i dont want to) or are either not helpfull to me.
Any ideas? I have a feeling i'm very close to my goal but i can't seem to grasp what i'm missing.

答:
You need to add @XmlElementWrapper(name = "LETTERS") annotation to getLetters() method like this

```<code>@XmlElementWrapper(name = "LETTERS")
@XmlElement(name = "LETTER")
public List<Letter> getLetters() {
    return letters;
}
</code>```

Body:
<?xml version="1.0" encoding="UTF-8"?>

<STATUS_UPDATE>
    <UPDATES_COUNTER>2</UPDATES_COUNTER>
    <LETTERS>
        <LETTER>
            <LETTER_KEY>key1</LETTER_KEY>
            <STATUS>status1</STATUS>
        </LETTER>
        <LETTER>
            <LETTER_KEY>key2</LETTER_KEY>
            <STATUS>status2</STATUS>
        </LETTER>
    </LETTERS>
</STATUS_UPDATE>

So i have this xml. Im trying to create a pojo from it.

@XmlRootElement(name = "STATUS_UPDATE")
public class StatusUpdate {

    private int updatesCounter;

    List<Letter> letters;

    public StatusUpdate(){
        letters = new ArrayList<Letter>();
    }

    public StatusUpdate(int updatesCounter, List<Letter> letters){
        super();
        this.updatesCounter = updatesCounter;
        this.letters =  letters;
    }

    @XmlElement(name="LETTERS")
    public List<Letter> getLetters() {
        return letters;
    }

    public void setLetters(List<Letter> letters) {
        this.letters = letters;
    }
    @XmlElement(name="UPDATES_COUNTER")
    public int getUpdatesCounter() {
        return updatesCounter;
    }

    public void setUpdatesCounter(int updatesCounter) {
        this.updatesCounter = updatesCounter;
    }

}

And letter class

@XmlRootElement(name = "LETTER")
public class Letter {

    public Letter(){

    }

    public Letter(String letterKey,String status){
        this.letterKey = letterKey;
        this.status = status;
    }
    String letterKey;
    String status;

    @XmlElement(name="LETTER_KEY")
    public String getLetterKey() {
        return letterKey;
    }
    public void setLetterKey(String letterKey) {
        this.letterKey = letterKey;
    }
    @XmlElement(name="STATUS")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}

and this code snipper wont seem to do the job.
i get no errors, code runs, i get a 2 in my updateCounter variable,
but my list is empty with only one letter object, with both variables null.

File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(StatusUpdate.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StatusUpdate msgObject = (StatusUpdate) jaxbUnmarshaller.unmarshal(file);

I've been reading the documentations and examples, but most of them are either written to match variable names and xml elemenets (which i dont want to) or are either not helpfull to me.
Any ideas? I have a feeling i'm very close to my goal but i can't seem to grasp what i'm missing.

Body:
You need to add @XmlElementWrapper(name = "LETTERS") annotation to getLetters() method like this

@XmlElementWrapper(name = "LETTERS")
@XmlElement(name = "LETTER")
public List<Letter> getLetters() {
    return letters;
}


问:
stl vector reserve
I was trying to pre-allocate a vector of integer like this

```<code>vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;
</code>```

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

答:
You are rather lucky that it didn't crash.

```<code>tmp_color[tmp_color_idx] = tmp_color_idx;
</code>```

In the above line, you are accessing out of bounds of the vector.

reserve() doesn't increase the size of the vector, resize() should be used.
To me, the method used by Elalfer is even better to pre-allocate the size.

Title: stl vector reserve

Body:
I was trying to pre-allocate a vector of integer like this

vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

Body:
You are rather lucky that it didn't crash.

tmp_color[tmp_color_idx] = tmp_color_idx;

In the above line, you are accessing out of bounds of the vector.

reserve() doesn't increase the size of the vector, resize() should be used.
To me, the method used by Elalfer is even better to pre-allocate the size.


问:
Register new constraint validator for standard bean validation annotation
I'm wondering whether it's possible to register new constraint validator of some custom type to a annotation defined by Bean Validation specification.
For example, let's image I have a class that accumulates several int values

```<code>public class IntContainer
{
  private int value1;
  private int value2;

  public int getValue1()
  {
    return value1;
  }

  public void setValue1(final int value1)
  {
    this.value1 = value1;
  }

  public int getValue2()
  {
    return value2;
  }

  public void setValue2(final int value2)
  {
    this.value2 = value2;
  }
}
</code>```

I would like to register a custom constraint validator to support the @Positive annotation for this type (instead of created a custom annotation).

```<code>public class PositiveIntContainerValidator implements ConstraintValidator<Positive, IntContainer>
{
  @Override
  public boolean isValid(final IntContainer value, final ConstraintValidatorContext context)
  {
    //TODO: do some validation here based on IntContainer state
    return false;
  }
}
</code>```

So that later I can use this:

```<code>@Positive
private IntContainer valueContainer;
</code>```

答:
A fully qualified name of your validator can be added to META-INF/services/javax.validation.ConstraintValidator file. This would allow Hibernate Validator to pick up your validator and it will be used for your custom types.

See more details if needed in this post (section "Use standard constraints for non standard classes")

Body:
I'm wondering whether it's possible to register new constraint validator of some custom type to a annotation defined by Bean Validation specification.
For example, let's image I have a class that accumulates several int values

public class IntContainer
{
  private int value1;
  private int value2;

  public int getValue1()
  {
    return value1;
  }

  public void setValue1(final int value1)
  {
    this.value1 = value1;
  }

  public int getValue2()
  {
    return value2;
  }

  public void setValue2(final int value2)
  {
    this.value2 = value2;
  }
}

I would like to register a custom constraint validator to support the @Positive annotation for this type (instead of created a custom annotation).

public class PositiveIntContainerValidator implements ConstraintValidator<Positive, IntContainer>
{
  @Override
  public boolean isValid(final IntContainer value, final ConstraintValidatorContext context)
  {
    //TODO: do some validation here based on IntContainer state
    return false;
  }
}

So that later I can use this:

@Positive
private IntContainer valueContainer;


答:
Full blogpost for the same : Download File in Angular Js2 Application

Below is working for me , you can try out that , one thing you missed out that is RequestOptions({responseType: ResponseContentType.Blob}), another thing you missed is : <Blob>response.blob()

```<code>   ngOnInit(): void {
    this.getFile("http://localhost:1800/api/demo/GetTestFile")
    .subscribe(fileData =>
      {
      let b:any = new Blob([fileData], { type: 'application/zip' });
      var url= window.URL.createObjectURL(b);
        window.open(url);
      }
    );
  }

   public getFile(path: string):Observable<any>{
    let options = new RequestOptions({responseType: ResponseContentType.Blob});
    return this.http.get(path, options)
        .map((response: Response) => <Blob>response.blob())  ;
  }
</code>```

Title: Angular JS empty pdf in new window

Body:
The problem is when i want to create PDF with angular js the file is empty

This is the scenario:

I have rest api, when i make get request response payload is like this :

JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDE4NT4+c3RyZWFtCnicpY4xD4JADIX3+xVvxEV7PeDAUYXBSZNzMg4EkGgCRIiD/144B41RNCF9aZO2r18vYmGE8hGQD5OJyIitYKz7rgR10efAZZhSzGIJSTBH4UzMud99rhDS8tXkMbTmqf9mJDtuCuEkbdYpexSr/iah+HB3f+hqZv/6TmQVQqtBZFVXt7K+trs2b0bSQhc+0wAsbk5Y5Smoc9DcCsvIgEnqkWylf7A3SQMeCXG1Bw4HIPIvwB0h835eCmVuZHN0cmVhbQplbmRvYmoKMSAwIG9iago8PC9UYWJzL1MvR3JvdXA8PC9TL1RyYW5zcGFyZW5jeS9UeXBlL0dyb3VwL0NTL0RldmljZVJHQj4+L0NvbnRlbnRzIDMgMCBSL1R5cGUvUGFnZS9SZXNvdXJjZXM8PC9Db2xvclNwYWNlPDwvQ1MvRGV2aWNlUkdCPj4vUHJvY1NldCBbL1BERiAvVGV4dCAvSW1hZ2VCIC9JbWFnZUMgL0ltYWdlSV0vRm9udDw8L0YxIDIgMCBSPj4+Pi9QYXJlbnQgNCAwIFIvTWVkaWFCb3hbMCAwIDU5NSA4NDJdPj4KZW5kb2JqCjUgMCBvYmoKWzEgMCBSL1hZWiAwIDg1MiAwXQplbmRvYmoKMiAwIG9iago8PC9TdWJ0eXBlL1R5cGUxL1R5cGUvRm9udC9CYXNlRm9udC9IZWx2ZXRpY2EvRW5jb2RpbmcvV2luQW5zaUVuY29kaW5nPj4KZW5kb2JqCjQgMCBvYmoKPDwvS2lkc1sxIDAgUl0vVHlwZS9QYWdlcy9Db3VudCAxL0lUWFQoMi4xLjcpPj4KZW5kb2JqCjYgMCBvYmoKPDwvTmFtZXNbKEpSX1BBR0VfQU5DSE9SXzBfMSkgNSAwIFJdPj4KZW5kb2JqCjcgMCBvYmoKPDwvRGVzdHMgNiAwIFI+PgplbmRvYmoKOCAwIG9iago8PC9OYW1lcyA3IDAgUi9UeXBlL0NhdGFsb2cvUGFnZXMgNCAwIFIvVmlld2VyUHJlZmVyZW5jZXM8PC9QcmludFNjYWxpbmcvQXBwRGVmYXVsdD4+Pj4KZW5kb2JqCjkgMCBvYmoKPDwvTW9kRGF0ZShEOjIwMTcxMjA1MTgwNDM5KzAxJzAwJykvQ3JlYXRvcihKYXNwZXJSZXBvcnRzIExpYnJhcnkgdmVyc2lvbiA2LjEuMCkvQ3JlYXRpb25EYXRlKEQ6MjAxNzEyMDUxODA0MzkrMDEnMDAnKS9Qcm9kdWNlcihpVGV4dCAyLjEuNyBieSAxVDNYVCk+PgplbmRvYmoKeHJlZgowIDEwCjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDI2NyAwMDAwMCBuIAowMDAwMDAwNTQzIDAwMDAwIG4gCjAwMDAwMDAwMTUgMDAwMDAgbiAKMDAwMDAwMDYzMSAwMDAwMCBuIAowMDAwMDAwNTA4IDAwMDAwIG4gCjAwMDAwMDA2OTQgMDAwMDAgbiAKMDAwMDAwMDc0OCAwMDAwMCBuIAowMDAwMDAwNzgwIDAwMDAwIG4gCjAwMDAwMDA4ODMgMDAwMDAgbiAKdHJhaWxlcgo8PC9JbmZvIDkgMCBSL0lEIFs8MzlhYzY4ZDI4YjM4ZGYwNDcwNDM2YTM4ZjA2ZjI2MjY+PGMxNDNkNzJiMDE5M2ZmYzM5ZDMyM2UxNzlhN2QyNDdjPl0vUm9vdCA4IDAgUi9TaXplIDEwPj4Kc3RhcnR4cmVmCjEwNTAKJSVFT0YK

The response headers are

:

and the pdf is ok, with data in it.

The problem is when i make http get from angular :

$scope.confirmPayment = function(){
    $http.get(apiUrl).then(function(response) {
        console.log(response.data);
        var data = new Blob([response.data], { type: "application/pdf" });
        var fileURL = URL.createObjectURL(data);
        window.open(fileURL);
    });
};

the pdf is empty. why is this happening and how to fix it? The response payload in both requests is the same.

response headers in second call are:

console log is printing this

%PDF-1.4
%����
3 0 obj
<</Filter/FlateDecode/Length 178>>stream
x���1��@�����7⢽�w����mƁ��L������1�&�/m���녖�|�9kbK;�l���w��y �5���ŰG�&���>W�Y�j
���T��ٍے���w��ũ��(?���������ŏ`�Ads;7U1����������.2p����V���2#پ��ަ-d$$0!$�����w6~{�
endstream
endobj
1 0 obj
<</Tabs/S/Group<</S/Transparency/Type/Group/CS/DeviceRGB>>/Contents 3 0 R/Type/Page/Resources<</ColorSpace<</CS/DeviceRGB>>/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]/Font<</F1 2 0 R>>>>/Parent 4 0 R/MediaBox[0 0 595 842]>>
endobj
5 0 obj
[1 0 R/XYZ 0 852 0]
endobj
2 0 obj
<</Subtype/Type1/Type/Font/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
4 0 obj
<</Kids[1 0 R]/Type/Pages/Count 1/ITXT(2.1.7)>>
endobj
6 0 obj
<</Names[(JR_PAGE_ANCHOR_0_1) 5 0 R]>>
endobj
7 0 obj
<</Dests 6 0 R>>
endobj
8 0 obj
<</Names 7 0 R/Type/Catalog/Pages 4 0 R/ViewerPreferences<</PrintScaling/AppDefault>>>>
endobj
9 0 obj
<</ModDate(D:20171205182420+01'00')/Creator(JasperReports Library version 6.1.0)/CreationDate(D:20171205182420+01'00')/Producer(iText 2.1.7 by 1T3XT)>>
endobj
xref
0 10
0000000000 65535 f
0000000260 00000 n
0000000536 00000 n
0000000015 00000 n
0000000624 00000 n
0000000501 00000 n
0000000687 00000 n
0000000741 00000 n
0000000773 00000 n
0000000876 00000 n
trailer
<</Info 9 0 R/ID [<1e77577afe299f8055a81e3d5141da79><eaf48da4dde2751fa6380537fbce1a72>]/Root 8 0 R/Size 10>>
startxref
1043
%%EOF
controller.home.js:7:7

Body:
Full blogpost for the same : Download File in Angular Js2 Application

Below is working for me , you can try out that , one thing you missed out that is RequestOptions({responseType: ResponseContentType.Blob}), another thing you missed is : <Blob>response.blob()

   ngOnInit(): void {
    this.getFile("http://localhost:1800/api/demo/GetTestFile")
    .subscribe(fileData =>
      {
      let b:any = new Blob([fileData], { type: 'application/zip' });
      var url= window.URL.createObjectURL(b);
        window.open(url);
      }
    );
  }

   public getFile(path: string):Observable<any>{
    let options = new RequestOptions({responseType: ResponseContentType.Blob});
    return this.http.get(path, options)
        .map((response: Response) => <Blob>response.blob())  ;
  }


问:
Angular 2/4 get the multiple selected items from dropdown or multi select list box
I need the multiple selected values based on the user selection from the multi-select/dropdown in angular/typescript

```<code><select multiple>
  <option value="Value1">Value1</option>
  <option value="Value2">Value2</option>
  <option value="Value3">Value3</option>
</select>
</code>```

Need an array of selected values

I'm not getting the value.

答:
You should try using a library like Angular Material:

HTML:

```<code><mat-form-field>
  <mat-select placeholder="Items" [formControl]="items" multiple>
    <mat-option *ngFor="let item of itemList" [value]="item">{{item}}</mat-option>
  </mat-select>
</mat-form-field>
</code>```

TS:

```<code>import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  items = new FormControl();

  itemList = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6'];
}
</code>```

Source: Angular Material Docs

Body:
I need the multiple selected values based on the user selection from the multi-select/dropdown in angular/typescript

<select multiple>
  <option value="Value1">Value1</option>
  <option value="Value2">Value2</option>
  <option value="Value3">Value3</option>
</select>

Need an array of selected values

I'm not getting the value.

Body:
You should try using a library like Angular Material:

HTML:

<mat-form-field>
  <mat-select placeholder="Items" [formControl]="items" multiple>
    <mat-option *ngFor="let item of itemList" [value]="item">{{item}}</mat-option>
  </mat-select>
</mat-form-field>

TS:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  items = new FormControl();

  itemList = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6'];
}

Source: Angular Material Docs


问:
How can I force the driver to click on a pop up on a page which has not completed loading
I'm using java with selenium IEDriverServer. I would like to know if is possible to click on a pop up on a page which has not completed loading. When I get the pop up, my code is not running until I click on Ok on pop up.

Thanks.

答:
It's not possible to click on element that is not visible.

But you can add the following config, it will tell the driver to implicitly wait for elements:

```<code>    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
</code>```

Body:
It's not possible to click on element that is not visible.

But you can add the following config, it will tell the driver to implicitly wait for elements:

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


问:
Unit testing when part of the class needs to be mocked
I have a class that I am trying to unit test.  This class extends another class that I am not interested in unit testing at this time.

The following code is an over simplification of the code I am trying to test.

```<code>package com.example.somePackage;
public class ApiBase {
  protected <T extends SomeClass> t getApi(Class<T> apiClass) {/* some logic*/}
}

package com.example.anotherPackage;
public MagicApiImpl extends ApiBase {
  private final MagicApiHandler apiHandler = new MagicApiHandler();

  public String doSomeStuff(String someString) {
    final BookApi bookApi = getApi(BookApi.class);
    // some logic
    return apiHandler.someMethod(bookApi, someString);
  }
}
</code>```

I would like to test doSomeStuff() on MagicApiImpl The part I would like to mock is what comes back in getApi().

At first go I tried simply creating an Instance of MagicApiImpl and setting all the behind the scenes things that happen but that started to become over complex for the scenario I want to test and the number of times I need to test it in other classes.  I will handle the testing of the logic in getApi() in a test of its own.

It would be helpful to use EasyMock to test this as it is what a majority of the tests for this project are written in but I would not be overly apposed to using mockito.

Edit

Okay I was reading about the Mockito.spy()  That would have been wonderful but sadly getApi is protected and in another package.  Worst case I could fall back on placing all the tests in that package but that makes it difficult track code.

答:
Using Easymock partial mocks your test should look like this:

```<code>    @Test
    public void test() {
        MagicApiImpl impl = EasyMock.createMockBuilder(MagicApiImpl.class)
            .addMockedMethod("getApi")
            .createMock();
        EasyMock.expect(impl.getApi(BookApi.class)).andReturn(/**Wharever you need*/);
        EasyMock.replay(impl);
        String input = "INPUT";
        String output = impl.doSomeStuff(input);
        System.out.println("The OUTPUT is: " + output);
        EasyMock.verify(impl);
        //Run asserts here
    }
</code>```

Reference: http://easymock.org/user-guide.html#mocking-partial

Body:
I have a class that I am trying to unit test.  This class extends another class that I am not interested in unit testing at this time.

The following code is an over simplification of the code I am trying to test.

package com.example.somePackage;
public class ApiBase {
  protected <T extends SomeClass> t getApi(Class<T> apiClass) {/* some logic*/}
}

package com.example.anotherPackage;
public MagicApiImpl extends ApiBase {
  private final MagicApiHandler apiHandler = new MagicApiHandler();

  public String doSomeStuff(String someString) {
    final BookApi bookApi = getApi(BookApi.class);
    // some logic
    return apiHandler.someMethod(bookApi, someString);
  }
}

I would like to test doSomeStuff() on MagicApiImpl The part I would like to mock is what comes back in getApi().

At first go I tried simply creating an Instance of MagicApiImpl and setting all the behind the scenes things that happen but that started to become over complex for the scenario I want to test and the number of times I need to test it in other classes.  I will handle the testing of the logic in getApi() in a test of its own.

It would be helpful to use EasyMock to test this as it is what a majority of the tests for this project are written in but I would not be overly apposed to using mockito.

Edit

Okay I was reading about the Mockito.spy()  That would have been wonderful but sadly getApi is protected and in another package.  Worst case I could fall back on placing all the tests in that package but that makes it difficult track code.

Body:
Using Easymock partial mocks your test should look like this:

    @Test
    public void test() {
        MagicApiImpl impl = EasyMock.createMockBuilder(MagicApiImpl.class)
            .addMockedMethod("getApi")
            .createMock();
        EasyMock.expect(impl.getApi(BookApi.class)).andReturn(/**Wharever you need*/);
        EasyMock.replay(impl);
        String input = "INPUT";
        String output = impl.doSomeStuff(input);
        System.out.println("The OUTPUT is: " + output);
        EasyMock.verify(impl);
        //Run asserts here
    }

Reference: http://easymock.org/user-guide.html#mocking-partial


问:
Turn a regular Windows program into a Windows Service
NetoSoft has a simple tool to create a Windows Service from a regular application. It does work, but obviously is unmaintained now. The tool allows you to register and unregister a service and to start and stop it.

Is there a more up-to-date tool that does this?

答: You can create a windows service in Visual Studio pretty easily.  Just move the appropriate parts of your code over as well.</p>