问:
JSON API delete 'has and belongs to many' relationship
I'm building an API for a cart-like thing with the jsonapi-resources gem, and I need an endpoint to remove an item from the cart.

Currently, I'm assuming that a client consuming this API won't need the actual 'cart items'. Instead it just needs a list of the products that are in the cart.

However, there doesn't seem to be any way to delete something in jsonapi-resources  without knowing that thing's ID. I.e. there's no way for a client to remove something from the cart without it knowing the id of the join model.

Basically I need an endpoint that does something like:

DELETE http://example.com/carts/1/cart-items?filter[product]=1

Instead, the only option I can find is

DELETE http://example.com/cart-items/1

Alternatively, I could implement a custom action to handle this, but I've gone through the docs and I can't find a prescribed way of writing custom actions.

答:
After struggling with this for hours, in the process of writing this question I finally worked out the answer. It's not at all well documented, though — I had to read through the gem's tests to work it out.

curl -X DELETE -H "Content-Type: application/vnd.api+json" \
--data '{ "data" : [{"type": "products", "id": 185 }]  }' \ http://localhost:3000/api/v1/carts/4085/relationships/products

This successfully deleted the item from the cart (and did not touch the product record itself).


来源: stackexchange

问:
why does resizing image in Pillow-python remove Image.format?
I'm resizing images in python using Pillow

```<code>image = Image.open("image_file.jpg")

print(image.format) # Prints JPEG

resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)

print(resized_image.format) # Prints None!!
</code>```

Why does resized_image.format Hold a None Value?

And How can i retain the format when resizing using pillow?

答:
You can save the resized images with save comments

```<code>resized_image.save("New_image.png")
</code>```

It will save into your current directory.

If you want to see in the python console itself you have to run

```<code>resized_image.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm resizing images in python using Pillow

image = Image.open("image_file.jpg")

print(image.format) # Prints JPEG

resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)

print(resized_image.format) # Prints None!!

Why does resized_image.format Hold a None Value?

And How can i retain the format when resizing using pillow?

Body:
You can save the resized images with save comments

resized_image.save("New_image.png")

It will save into your current directory.

If you want to see in the python console itself you have to run

resized_image.show()


问:
Add directives from directive in AngularJS but keep ng-model binded
This question is linked to following question:

Add directives from directive in AngularJS

In suggested answer, there's problem that ng-model is not updating because element is being compiled in directive.
What I expected is that, after I change select option, ng-model will be binded to selected item, but it's not.
Is there any way to fix it?

Plunker: http://plnkr.co/edit/Tw1Pbt?p=preview

Specificly:

```<code>  <select ng-options="s for s in selects" ng-model="el" common-things>
  <option value=""></option>
</select>
{{el}}
</code>```

Here ng-model (el) has always same value, no matter what option I choos from select

Same problem is if I have isolated scope inside directive, for instance:

```<code>         <input type=text common-things ng-model="el.val"                otherdata="something"/>
</code>```

I eexpect, as I write something inside input, that {{el.val}} would have that value, but it's not being updated.

答:
Your additional directive creates a new scope for the <select> element. Due to JavaScript Prototype Inheritance, the property el ends up on the directive's scope rather than the parent controller's scope.  This is a common pitfall, and a major reason to always use a dot in angular bindings.

The quick fix for this is to define el on the main controller as an object, and set a property of the object.

```<code>$scope.el = {};
$scope.el.val=2;

<select ng-options="s for s in selects" ng-model="el.val" common-things>
</code>```

Demo

Body:
This question is linked to following question:

Add directives from directive in AngularJS

In suggested answer, there's problem that ng-model is not updating because element is being compiled in directive.
What I expected is that, after I change select option, ng-model will be binded to selected item, but it's not.
Is there any way to fix it?

Plunker: http://plnkr.co/edit/Tw1Pbt?p=preview

Specificly:

  <select ng-options="s for s in selects" ng-model="el" common-things>
  <option value=""></option>
</select>
{{el}}

Here ng-model (el) has always same value, no matter what option I choos from select

Same problem is if I have isolated scope inside directive, for instance:

         <input type=text common-things ng-model="el.val"                otherdata="something"/>

I eexpect, as I write something inside input, that {{el.val}} would have that value, but it's not being updated.

Body:
Your additional directive creates a new scope for the <select> element. Due to JavaScript Prototype Inheritance, the property el ends up on the directive's scope rather than the parent controller's scope.  This is a common pitfall, and a major reason to always use a dot in angular bindings.

The quick fix for this is to define el on the main controller as an object, and set a property of the object.

$scope.el = {};
$scope.el.val=2;

<select ng-options="s for s in selects" ng-model="el.val" common-things>

Demo


问:
searching controller in a web application
I am new to Spring-mvc. In my first tutorial I am having a doubt, we create a servelet of DispatcherServlet in web.xml and mark our controller using @contorller annotation.
Then using @Requestmapping annotation we filter url for function to be invoked.

How Spring searches for controller in the webapp?
Which function actually invoked in  DispatcherServelet to create a instance of controller class?
Can i have multiple controller in my application?

答:
How Spring searches for controller in the webapp?

Spring container scans through all of the packages specified through @ComponentScan annotation (or using component-scan in xml config) and when you mark your bean class with stereotype annotation like @Controller, Spring container will create the instance (by default singleton scope) of your controller class and maps the url along with the request method type(like GET, POST, PUT, etc..). The other stereotype annotation are listed here (like @Service, etc..) and the container creates objects for these types as well.

Which function actually invoked in DispatcherServelet to create a
  instance of controller class?

Spring core container creates the instances for all beans annotated with stereotypes (as explained above during container start up) and then
Dispatcherservlet uses HandlerMapping to map the urls to the controller methods and RequestMappingHandlerMapping implementation is being used by default and when the request comes, it will be delegated to the respective the controller method, you can look here.

Can I have multiple controllers in my application?

Yes, you can define multiple controllers in your application. In a typical web application project, you would see many controller classes each mapped with the respective urls and the business logic being handled through their service classes.

I suggest you refer this to understand on how the spring web flow works.


问:
Findbugs android gradle plugin
I have an android project. I want to introduce findbugs in my project as a gradle plugin. I tried to edit the project's build.gradle as below.

```<code>buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
           }
dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0+'
    classpath 'io.fabric.tools:gradle:1.+'

    }
}

apply plugin: "java"
apply plugin: "findbugs"
findbugs {
  toolVersion = "2.0.1"
  sourceSets = [sourceSets.main]
  ignoreFailures = false
  reportsDir = file("$project.buildDir/findbugsReports")
  effort = "max"
  reportLevel = "high"
  includeFilter =     file("$rootProject.projectDir/config/findbugs/includeFilter.xml")
  excludeFilter = file("$rootProject.projectDir/config/findbugs/excludeFilter.xml")
 }
</code>```

Is this plugin correct?
 Does anything neeed to be added or removed?
Now what should I do to get the results of this findbugs check?
What gradle command should I use?

答:
Please take a look at this project https://github.com/Piasy/AndroidCodeQualityConfig.

This project including lint, pmd, findbugs, checkstyle, jacoco code coverage.And support project with submodules.

Title: Findbugs android gradle plugin

Body:
I have an android project. I want to introduce findbugs in my project as a gradle plugin. I tried to edit the project's build.gradle as below.

buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
           }
dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0+'
    classpath 'io.fabric.tools:gradle:1.+'

    }
}

apply plugin: "java"
apply plugin: "findbugs"
findbugs {
  toolVersion = "2.0.1"
  sourceSets = [sourceSets.main]
  ignoreFailures = false
  reportsDir = file("$project.buildDir/findbugsReports")
  effort = "max"
  reportLevel = "high"
  includeFilter =     file("$rootProject.projectDir/config/findbugs/includeFilter.xml")
  excludeFilter = file("$rootProject.projectDir/config/findbugs/excludeFilter.xml")
 }

Is this plugin correct?
 Does anything neeed to be added or removed?
Now what should I do to get the results of this findbugs check?
What gradle command should I use?


问:
How can I use the qsort() function with this struct?
I have these structs,

```<code>    typedef struct
{
  char *str; //register to store each element (one string)

} v_elemento;

/**
* this register has an array of elements, a counter for the size and another for the capacity
*/
typedef struct
{
  /** numero de elementos do vetor */
  int tamanho; //size

  /** capacidade do vetor */
  int capacidade; //capacity

  /** array of stored elements */
  v_elemento* elementos;

} vetor;
</code>```

I heard that there is a qsort() function that allows me to sort an array, I tried checking the internet but all examples either use int, float or strings.  How can I use the qsort() function using the structures above?

I want something like this

```<code>   for(int i=0; i<vetor->tamanho;i++)
//sorts vetor->elemento[i].str
</code>```

This is my cmp function;

```<code>int compara(v_elemento *p0,v_elemento *p1){
      return strcmp(p0->str,p1->str);
}
</code>```

This is my qsort() function:

```<code>qsort(vec->elementos,vec->tamanho, sizeof(v_elemento),compara)
</code>```

Im gonna show you a code, which is working properly, it sorts what I want but it's selection sort:

```<code>int vetor_ordena_sel(vetor* vec)
{

        //special cases
        if(vec==NULL)
            return -1;
        if(vec->tamanho<=1) // already sorted
            return 0;
        // special cases

        int i, j, posicao; //posicao is position

        char *min_tmp;

        for(i=0;i<(vec->tamanho);i++){
            posicao=i;
            for(j=i+1;j<(vec->tamanho);j++){
                if(strcmp(vec->elementos[j].str,vec->elementos[posicao].str)<0)
                    posicao=j;
            }

                if(posicao!=i){
                    min_tmp=vec->elementos[i].str;
                    vec->elementos[i].str=vec->elementos[posicao].str;
                    vec->elementos[posicao].str=min_tmp;
                }
        }

                    return 0;
    }
</code>```

Am I doing something wrong?

答:
When writing comparison function for builtin sort functions, the pass in parameter should really be const void * instead of any other type. Please refer to documentation.

I don't know the difference between "capacity" and "size" in that struct, but as you use the size variable in qsort, I'll do the same.

The following comparator works under gcc 4.2.1.

```<code>int compara(const void *p0, const void *p1)
{
    return strcmp(((v_elemento *)p0)->str, ((v_elemento *)p1)->str);
}
</code>```

As I said above, you should only pass in const void *, so I made a type casting.

Below is the driver code I wrote:

```<code>// Test case.
vetor *vec = malloc(sizeof(vetor));
vec->tamanho = 5;
vec->elementos = malloc(5 * sizeof(v_elemento));
vec->elementos[0].str = "This";
vec->elementos[1].str = "is";
vec->elementos[2].str = "a";
vec->elementos[3].str = " test";
vec->elementos[4].str = "string.";

// Sort.
qsort(vec->elementos, vec->tamanho, sizeof(v_elemento), compara);

// Print result.
for (int i = 0; i < 5; ++i) {
    printf("%s\n", vec->elementos[i].str);
}

// Clean up.
free(vec->elementos);
free(vec);
</code>```

And the output result is:

```<code> test
This
a
is
string.
</code>```

Note that there is a space in the string ranked first. :-)

Body:
I have these structs,

    typedef struct
{
  char *str; //register to store each element (one string)

} v_elemento;

/**
* this register has an array of elements, a counter for the size and another for the capacity
*/
typedef struct
{
  /** numero de elementos do vetor */
  int tamanho; //size

  /** capacidade do vetor */
  int capacidade; //capacity

  /** array of stored elements */
  v_elemento* elementos;

} vetor;

I heard that there is a qsort() function that allows me to sort an array, I tried checking the internet but all examples either use int, float or strings.  How can I use the qsort() function using the structures above?

I want something like this

   for(int i=0; i<vetor->tamanho;i++)
//sorts vetor->elemento[i].str

This is my cmp function;

int compara(v_elemento *p0,v_elemento *p1){
      return strcmp(p0->str,p1->str);
}

This is my qsort() function:

qsort(vec->elementos,vec->tamanho, sizeof(v_elemento),compara)

Im gonna show you a code, which is working properly, it sorts what I want but it's selection sort:

int vetor_ordena_sel(vetor* vec)
{

        //special cases
        if(vec==NULL)
            return -1;
        if(vec->tamanho<=1) // already sorted
            return 0;
        // special cases

        int i, j, posicao; //posicao is position

        char *min_tmp;

        for(i=0;i<(vec->tamanho);i++){
            posicao=i;
            for(j=i+1;j<(vec->tamanho);j++){
                if(strcmp(vec->elementos[j].str,vec->elementos[posicao].str)<0)
                    posicao=j;
            }

                if(posicao!=i){
                    min_tmp=vec->elementos[i].str;
                    vec->elementos[i].str=vec->elementos[posicao].str;
                    vec->elementos[posicao].str=min_tmp;
                }
        }

                    return 0;
    }

Am I doing something wrong?

Body:
When writing comparison function for builtin sort functions, the pass in parameter should really be const void * instead of any other type. Please refer to documentation.

I don't know the difference between "capacity" and "size" in that struct, but as you use the size variable in qsort, I'll do the same.

The following comparator works under gcc 4.2.1.

int compara(const void *p0, const void *p1)
{
    return strcmp(((v_elemento *)p0)->str, ((v_elemento *)p1)->str);
}

As I said above, you should only pass in const void *, so I made a type casting.

Below is the driver code I wrote:

// Test case.
vetor *vec = malloc(sizeof(vetor));
vec->tamanho = 5;
vec->elementos = malloc(5 * sizeof(v_elemento));
vec->elementos[0].str = "This";
vec->elementos[1].str = "is";
vec->elementos[2].str = "a";
vec->elementos[3].str = " test";
vec->elementos[4].str = "string.";

// Sort.
qsort(vec->elementos, vec->tamanho, sizeof(v_elemento), compara);

// Print result.
for (int i = 0; i < 5; ++i) {
    printf("%s\n", vec->elementos[i].str);
}

// Clean up.
free(vec->elementos);
free(vec);

And the output result is:

 test
This
a
is
string.

Note that there is a space in the string ranked first. :-)


问:
Win 10 app not running on minimizing
I have made a IoT beacon reading app. I am using DispatchTimer to get signal for 10 sec then processing it to retrieve some result. Everything is working fine if app is not minimized. but when app is minimized or I work on some other thing then App is not working at all. I have handle App suspended event but still on minimizing the app I am not able show the result.</p>

答:
To keep your app running when minimized, you need to create an ExtendedExecutionSession in your app. Read more details here:

https://msdn.microsoft.com/en-us/magazine/mt590969.aspx

Thanks,

Stefan Wick - Windows Developer Platform

Title: Win 10 app not running on minimizing


问:
Why protected members can be overridden by public members in TypeScript?
I am new to Typescript, and I tried to played around a little with TypeScript in this playground. I noticed that in TypeScript, a protected member in base class can be overridden by public members:

```<code>class Base {
    protected name: string = '!'
}

class Derived extends Base{
    public name: string = '?'
}
</code>```

On the one hand, this makes sense to me since the Liskov Substitution Principle still holds: base class has stricter requirements than derived class. But on the other hand, I noticed that private member cannot be overridden by protected or public one, which seems inconsistent to me:

```<code>class Base {
    private name: string = '!'
}

class Derived extends Base{
    public name: string = '?'  // ERROR!
}
</code>```

Thus I wonder:

Is my observation an intended behavior or a bug in Typescript?

If it's intended, why this inconsistency exists? Why not TypeScript requires all overriding members having the same accessibility as members in base class? Or allowing all derived members with higher accessibility overriding members in base class?

答:
This is intended behavior.

TypeScript compiles to JavaScript. Because of this, using access modifiers in your code has absolutely no effect on the output. The only thing that access modifiers do is let the compiler yell at you if you use something that you shouldn't be accessing.

Example: Both of these classes compile to the exact same code. Playground (ignore the class name)

```<code>// prop is private
class Test {
    private prop: string;
    constructor() {
        this.prop = "str"
    }
}

// prop is public
class Test {
    public prop: string;
    constructor() {
        this.prop = "str"
    }
}
</code>```

In languages like C#, private properties are truly private, and thus it is possible to inherit from a class with a private name property while exposing a name property. Inherited methods accessing this.name will access the name property in the base class, while methods in your class accessing this.name will use the property in the inheriting class.

Let's look at the emitted JavaScript for your example.

```<code>var __extends; // omitted for brevity
var Base = (function () {
    function Base() {
        this.name = '!';
    }
    return Base;
}());
var Derived = (function (_super) {
    __extends(Derived, _super);
    function Derived() {
        var _this = _super.apply(this, arguments) || this;
        _this.name = '?';
        return _this;
    }
    return Derived;
}(Base));
</code>```

As you can see, what happens here is the Base class assigns ! to this.name, Derived then changes the supposedly private name property of Base to ?. Obviously, this could result in some incredibly confusing bugs when methods in the Base class refer to this.name and get the unexpected value assigned by the Derived class.

Body:
I am new to Typescript, and I tried to played around a little with TypeScript in this playground. I noticed that in TypeScript, a protected member in base class can be overridden by public members:

class Base {
    protected name: string = '!'
}

class Derived extends Base{
    public name: string = '?'
}

On the one hand, this makes sense to me since the Liskov Substitution Principle still holds: base class has stricter requirements than derived class. But on the other hand, I noticed that private member cannot be overridden by protected or public one, which seems inconsistent to me:

class Base {
    private name: string = '!'
}

class Derived extends Base{
    public name: string = '?'  // ERROR!
}

Thus I wonder:

Is my observation an intended behavior or a bug in Typescript?

If it's intended, why this inconsistency exists? Why not TypeScript requires all overriding members having the same accessibility as members in base class? Or allowing all derived members with higher accessibility overriding members in base class?

Body:
This is intended behavior.

TypeScript compiles to JavaScript. Because of this, using access modifiers in your code has absolutely no effect on the output. The only thing that access modifiers do is let the compiler yell at you if you use something that you shouldn't be accessing.

Example: Both of these classes compile to the exact same code. <a href="http://www.typescriptlang.org/play/#src=%2F%2F%20prop%20is%20_private_%0D%0Aclass%20Test%20%7B%0D%0A%20%20%20%20private%20prop%3A%20string%3B%0D%0A%20%20%20%20constructor()%20%7B%0D%0A%20%20%20%20%20%20%20%20this.prop%20%3D%20%22str%22%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A%2F%2F%20prop%20is%20_public_%0D%0Aclass%20Test2%20%7B%0D%0A%20%20%20%20public%20prop%3A%20string%3B%0D%0A%20%20%20%20constructor()%20%7B%0D%0A%20%20%20%20%20%20%20%20this.prop%20%3D%20%22str%22%0D%0A%20%20%20%20%7D%0D%0A%7D" rel="nofollow noreferrer">Playground (ignore the class name)

// prop is private
class Test {
    private prop: string;
    constructor() {
        this.prop = "str"
    }
}

// prop is public
class Test {
    public prop: string;
    constructor() {
        this.prop = "str"
    }
}

In languages like C#, private properties are truly private, and thus it is possible to inherit from a class with a private name property while exposing a name property. Inherited methods accessing this.name will access the name property in the base class, while methods in your class accessing this.name will use the property in the inheriting class.

Let's look at the emitted JavaScript for your example.

var __extends; // omitted for brevity
var Base = (function () {
    function Base() {
        this.name = '!';
    }
    return Base;
}());
var Derived = (function (_super) {
    __extends(Derived, _super);
    function Derived() {
        var _this = _super.apply(this, arguments) || this;
        _this.name = '?';
        return _this;
    }
    return Derived;
}(Base));

As you can see, what happens here is the Base class assigns ! to this.name, Derived then changes the supposedly private name property of Base to ?. Obviously, this could result in some incredibly confusing bugs when methods in the Base class refer to this.name and get the unexpected value assigned by the Derived class.


问:
Testing that a print function works (C)
I am trying to make a main function which will test a whole bunch of other functions to make sure that they work. That is, if they contain bugs, return 1, if no bugs, return 0

Suppose one of the functions I am trying to test is the following:

```<code>void list_print(list_t*list);
</code>```

this should print a list in "human-readable form" from first to last elements, between curly braces.

Now, naturally I could simply print an array and see for myself that it looks good, but I need to do this so that it is automatic, i.e. if the print function prints accurately, return 0, otherwise, return 1.

How do I go about doing this (in a general sort of way)? I keep googling and can't really find the answer.

答:
As a general answer to this sort of testing problem: you run it once on a given, fixed, input and you inspect the result. If it 'looks right' then you write a test that provides exactly the same input every time and blindly compares the output with the expected output, which is the output you 'manually' verified and it 'looks right'. This will prevent a regression in the function implementation.

You can go further and add a number of test cases (empty list, one entry in list, more entries etc) and then write a similar test for each case. These are 'expected result' tests, where the test does not know what the 'looks right' means, but it simply verifies that for a given input the output is the one 'expected' and it does not deviate. The outputs themselves are verified that they 'look right' by the person writing the test, which adds the 'expected output', manually, when the test is written and accepted.

The alternative is you have to write logic to parse the output, perhaps a full blown lexer and grammar, and truly validate the output. For this you need to very precisely define what output is 'right' and write an appropriate test parser for it. Is a worthy goal if the function is important enough, but this does not appear to be your case.

BTW, do not write a function that 'return 1 if the function has bugs', but instead use a test framework and add this as a build phase to your project.

Title: Testing that a print function works (C)

Body:
I am trying to make a main function which will test a whole bunch of other functions to make sure that they work. That is, if they contain bugs, return 1, if no bugs, return 0

Suppose one of the functions I am trying to test is the following:

void list_print(list_t*list);

this should print a list in "human-readable form" from first to last elements, between curly braces.

Now, naturally I could simply print an array and see for myself that it looks good, but I need to do this so that it is automatic, i.e. if the print function prints accurately, return 0, otherwise, return 1.

How do I go about doing this (in a general sort of way)? I keep googling and can't really find the answer.


问:
Help with debugging Qt code
Hi I got couple of questions regarding debugging Qt Code using QtCreator.

I primarily use mac for Qt development but also use win32. So to debug Qt code do I need to install debug library on both?

Say in my application I'm deleting a pointer twice. In small application I can just scan the code and figure out (at least I'll give it a try). In a big application I know I'm deleting location 003E0000 twice. Then what is the best way of determining what is being deleted and who are trying to delete it (preferably using debugger that comes with QtCreator).

答:
Yes you have to...

I suggest you to use valgrind memcheck. It works on linux and mac (I don't know whether it has windows version) and it replaces malloc and free methods and shows much information about memory handling.

valgrind --tool=memcheck

ContentLicense: CC BY-SA 2.5

Title: Help with debugging Qt code


问:
How to nest routes in React Router v4?
Is there a way to nest routes in React Router v4?

This works:

```<code>  <Router basename='/app'>
    <main>
      <Route path='/' component={AppBar} />
      <Route path='/customers' component={Customers} />
    </main>
  </Router>
</code>```

This does not:

```<code>  <Router basename='/app'>
    <Route path='/' component={AppBar}>
      <Route path='/customers' component={Customers} />
    </Route>
  </Router>
</code>```

Customers Component:

```<code>import React, { Component, PropTypes } from 'react'
import styled from 'styled-components'

export default class Customers extends Component {
  render () {
    return (
      <Container>
        <h1>Customers</h1>
      </Container>
    )
  }
}

const Container = styled.section`
  height: 100%;
  padding: 15px;
  overflow: auto;
`
</code>```

答:
I adapted this from the docs, seem to work so far. Probably missing something obvious, and yes it is not the v4 way but we need all the routes defined in one place.</p>

```<code>function RouteNest(props){ return (
  <Route exact={props.exact} path={props.path} render={ p => <props.component {...p} children={props.children}/> } />
)}

export const MainRoutes = props =>

<div className='content layout'>

  <Route exact path="/" component={Landing}/>
  <Route  path={'/contact'} component={Contact}/>

  <RouteNest  path={'/thing'} component={CompoWithSub}>
    <RouteNest  path={'/thing/suba'} component={SubComponentA}/>
    <RouteNest  path={'/thing/subb'} component={SubComponentB}/>
  </RouteNest>

</div>

export const CompoWithSub = props => <div>{props.children)</div>
</code>```

Title: How to nest routes in React Router v4?

Body:
Is there a way to nest routes in React Router v4?

This works:

  <Router basename='/app'>

      <Route path='/' component={AppBar} />
      <Route path='/customers' component={Customers} />

  </Router>

This does not:

  <Router basename='/app'>
    <Route path='/' component={AppBar}>
      <Route path='/customers' component={Customers} />
    </Route>
  </Router>

Customers Component:

import React, { Component, PropTypes } from 'react'
import styled from 'styled-components'

export default class Customers extends Component {
  render () {
    return (
      <Container>

Customers

      </Container>
    )
  }
}

const Container = styled.section`
  height: 100%;
  padding: 15px;
  overflow: auto;
`

Body:
I adapted this from the docs, seem to work so far. Probably missing something obvious, and yes it is not the v4 way but we need all the routes defined in one place.

function RouteNest(props){ return (
  <Route exact={props.exact} path={props.path} render={ p => <props.component {...p} children={props.children}/> } />
)}

export const MainRoutes = props =>

<div className='content layout'>

  <Route exact path="/" component={Landing}/>
  <Route  path={'/contact'} component={Contact}/>

  <RouteNest  path={'/thing'} component={CompoWithSub}>
    <RouteNest  path={'/thing/suba'} component={SubComponentA}/>
    <RouteNest  path={'/thing/subb'} component={SubComponentB}/>
  </RouteNest>

</div>

export const CompoWithSub = props => <div>{props.children)</div>


问:
mongodb error: 'longitude/latitude is out of bounds
when I run the mongoDB query, I get error which is  'longitude/latitude is out of bounds.

Here is my query is created:

```<code>DBObject query = new BasicDBObject("loc",
            new BasicDBObject("$geoWithin",
                    new BasicDBObject("$geometry",
                            new BasicDBObject("type","Polygon").append("coordinates", polygon))));
</code>```

Here is my mongoDB query:

```<code>db.collection_name.find(
   { "loc" :
        { "$geoWithin" :
            { "$geometry" :
                { "type" : "Polygon" , "coordinates" : [ [ [ 44.67047 , 136.01075] , [ 77.05318 , 33.59619] , [ 13.04135 , -22.31323]]]

                }
            }
        }
   }
)
</code>```

I get this error output:

```<code>{
"code" : {
    "_bsontype" : "Int32",
    "value" : 2
},
"codeName" : "BadValue",
"errmsg" : "longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011",
"message" : "longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011",
"name" : "MongoError",
"ok" : {
    "_bsontype" : "Double",
    "value" : 0
},
</code>```

How can I solve this problem ? Thank you for your answers.

答:
"longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011"

You need to specify in the order of longitude then latitude. The valid range of latitude in degrees is -90 and +90. Your value of latitude of 136.011 is out of range.

"Loop is not closed"

To specify geospatial query for $geometry you need to close the GeoJSON Polygon loop in order to create a polygon shape.

For example:

```<code>{
  type: "Polygon",
  coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0  ] ] ]
}
</code>```

Note that the first and last coordinates are matching, in order to close the polygon shape.

The above is assuming that you're referring to GeoJSON polygons with a single ring.

Body:
when I run the mongoDB query, I get error which is  'longitude/latitude is out of bounds.

Here is my query is created:

DBObject query = new BasicDBObject("loc",
            new BasicDBObject("$geoWithin",
                    new BasicDBObject("$geometry",
                            new BasicDBObject("type","Polygon").append("coordinates", polygon))));

Here is my mongoDB query:

db.collection_name.find(
   { "loc" :
        { "$geoWithin" :
            { "$geometry" :
                { "type" : "Polygon" , "coordinates" : [ [ [ 44.67047 , 136.01075] , [ 77.05318 , 33.59619] , [ 13.04135 , -22.31323]]]

                }
            }
        }
   }
)

I get this error output:

{
"code" : {
    "_bsontype" : "Int32",
    "value" : 2
},
"codeName" : "BadValue",
"errmsg" : "longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011",
"message" : "longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011",
"name" : "MongoError",
"ok" : {
    "_bsontype" : "Double",
    "value" : 0
},

How can I solve this problem ? Thank you for your answers.

Body:
"longitude/latitude is out of bounds, lng: 44.6705 lat: 136.011"

You need to specify in the order of longitude then latitude. The valid range of latitude in degrees is -90 and +90. Your value of latitude of 136.011 is out of range.

"Loop is not closed"

To specify geospatial query for $geometry you need to close the GeoJSON Polygon loop in order to create a polygon shape.

For example:

{
  type: "Polygon",
  coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0  ] ] ]
}

Note that the first and last coordinates are matching, in order to close the polygon shape.

The above is assuming that you're referring to GeoJSON polygons with a single ring.


问:
Retrieve Facebook Insights for all active ads within an account?
My code allows me to retrieve all ads that between certain dates, but this includes ads that are no longer active.

I want to show insights only for ACTIVE ads. How can I retrieve Facebook Insights for all active ads within an account?

```<code>public function getInsights($levelType, $id, $aggLevel, $start, $end) {
    if ($levelType) {
        if ($id == null) {
            abort(400, 'You must provide the ID for the object you want to retrieve.');
        }
    } else {
        $levelType = \AdAccount::class;
        $id = ACT_PREPEND . $this->fbConfig['account_id'];
        $aggLevel = AdsInsightsLevelValues::CAMPAIGN;
    }
    $variableClassWithNamespace = '\FacebookAds\Object\\' . $levelType; //TODO: avoid hard-coding class paths as strings
    $level = new $variableClassWithNamespace($id);
    $fields = [
        InsightsFields::SPEND,
        InsightsFields::CAMPAIGN_ID,
        InsightsFields::CAMPAIGN_NAME,
        InsightsFields::ADSET_ID,
        InsightsFields::ADSET_NAME,
        InsightsFields::AD_ID,
        InsightsFields::AD_NAME,
        InsightsFields::UNIQUE_IMPRESSIONS,
        InsightsFields::INLINE_LINK_CLICKS,
        InsightsFields::INLINE_LINK_CLICK_CTR,
        InsightsFields::COST_PER_INLINE_LINK_CLICK,
        InsightsFields::ACTIONS,
        InsightsFields::COST_PER_ACTION_TYPE,
        InsightsFields::CPM,
    ];
    $params = [
        AdReportRunFields::LEVEL => $aggLevel,
    ];
    if ($start) {
        $params[AdReportRunFields::TIME_RANGE]['since'] = $start;
        if (!$end) {
            $params[AdReportRunFields::TIME_RANGE]['until'] = (new \DateTime("+2 year"))->format('Y-m-d');
        }
    }
    if ($end) {
        $params[AdReportRunFields::TIME_RANGE]['until'] = $end;
        if (!$start) {
            $params[AdReportRunFields::TIME_RANGE]['since'] = (new \DateTime("-1 year"))->format('Y-m-d');
        }
    }
    if (!$start && !$end) {
        $params[AdReportRunFields::DATE_PRESET] = InsightsPresets::LIFETIME;
    }
    $insights = $level->getInsights($fields, $params);
    return $insights->getResponse()->getBody();
}
</code>```

I'm using the Facebook PHP Ads SDK 2.8 ("facebook/php-ads-sdk": "2.8.*" in composer.json). The documentation is here.

答:
You should use filtering on delivery_info to Active. It would be looks like the following in your http request

```<code>filtering:[{"field":"campaign.delivery_info","operator":"IN","value":["active"]}]
</code>```

Please refer to the filtering section in the document.

https://developers.facebook.com/docs/marketing-api/insights/parameters/v2.8

```<code>filtering
list<Filter Object>
Default value: Array
Filters on the report data. This parameter is an array of filter objects.
field
string
Required
operator
enum {EQUAL, NOT_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN, LESS_THAN_OR_EQUAL, IN_RANGE, NOT_IN_RANGE, CONTAIN, NOT_CONTAIN, IN, NOT_IN, STARTS_WITH, ANY, ALL, AFTER, BEFORE, NONE}
Required
value
string
</code>```

If you want to see the code, please check this filtering field in the PHP SDK. It's just mirroring the actual API fields

https://github.com/facebook/facebook-php-ads-sdk/blob/53bee21251a9d898591708b96d1afa9e13516e3d/src/FacebookAds/Object/Campaign.php#L220

Also, we recently launched a scenario based codegen wizard tool. You can walk through the "Create Ad Report" wizard, and it will generate code for you. (Although it only support Java for now)

The URL of the tool is: (replace your own app ID)
https://developers.facebook.com/apps/your_app_id/marketing-api/quickstart/

Body:
My code allows me to retrieve all ads that between certain dates, but this includes ads that are no longer active.

I want to show insights only for ACTIVE ads. How can I retrieve Facebook Insights for all active ads within an account?

public function getInsights($levelType, $id, $aggLevel, $start, $end) {
    if ($levelType) {
        if ($id == null) {
            abort(400, 'You must provide the ID for the object you want to retrieve.');
        }
    } else {
        $levelType = \AdAccount::class;
        $id = ACT_PREPEND . $this->fbConfig['account_id'];
        $aggLevel = AdsInsightsLevelValues::CAMPAIGN;
    }
    $variableClassWithNamespace = '\FacebookAds\Object\\' . $levelType; //TODO: avoid hard-coding class paths as strings
    $level = new $variableClassWithNamespace($id);
    $fields = [
        InsightsFields::SPEND,
        InsightsFields::CAMPAIGN_ID,
        InsightsFields::CAMPAIGN_NAME,
        InsightsFields::ADSET_ID,
        InsightsFields::ADSET_NAME,
        InsightsFields::AD_ID,
        InsightsFields::AD_NAME,
        InsightsFields::UNIQUE_IMPRESSIONS,
        InsightsFields::INLINE_LINK_CLICKS,
        InsightsFields::INLINE_LINK_CLICK_CTR,
        InsightsFields::COST_PER_INLINE_LINK_CLICK,
        InsightsFields::ACTIONS,
        InsightsFields::COST_PER_ACTION_TYPE,
        InsightsFields::CPM,
    ];
    $params = [
        AdReportRunFields::LEVEL => $aggLevel,
    ];
    if ($start) {
        $params[AdReportRunFields::TIME_RANGE]['since'] = $start;
        if (!$end) {
            $params[AdReportRunFields::TIME_RANGE]['until'] = (new \DateTime("+2 year"))->format('Y-m-d');
        }
    }
    if ($end) {
        $params[AdReportRunFields::TIME_RANGE]['until'] = $end;
        if (!$start) {
            $params[AdReportRunFields::TIME_RANGE]['since'] = (new \DateTime("-1 year"))->format('Y-m-d');
        }
    }
    if (!$start && !$end) {
        $params[AdReportRunFields::DATE_PRESET] = InsightsPresets::LIFETIME;
    }
    $insights = $level->getInsights($fields, $params);
    return $insights->getResponse()->getBody();
}

I'm using the Facebook PHP Ads SDK 2.8 ("facebook/php-ads-sdk": "2.8.*" in composer.json). The documentation is here.

Body:
You should use filtering on delivery_info to Active. It would be looks like the following in your http request

filtering:[{"field":"campaign.delivery_info","operator":"IN","value":["active"]}]

Please refer to the filtering section in the document.

https://developers.facebook.com/docs/marketing-api/insights/parameters/v2.8

filtering
list<Filter Object>
Default value: Array
Filters on the report data. This parameter is an array of filter objects.
field
string
Required
operator
enum {EQUAL, NOT_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN, LESS_THAN_OR_EQUAL, IN_RANGE, NOT_IN_RANGE, CONTAIN, NOT_CONTAIN, IN, NOT_IN, STARTS_WITH, ANY, ALL, AFTER, BEFORE, NONE}
Required
value
string

If you want to see the code, please check this filtering field in the PHP SDK. It's just mirroring the actual API fields

https://github.com/facebook/facebook-php-ads-sdk/blob/53bee21251a9d898591708b96d1afa9e13516e3d/src/FacebookAds/Object/Campaign.php#L220

Also, we recently launched a scenario based codegen wizard tool. You can walk through the "Create Ad Report" wizard, and it will generate code for you. (Although it only support Java for now)

The URL of the tool is: (replace your own app ID)
https://developers.facebook.com/apps/your_app_id/marketing-api/quickstart/


问:
What's the best way to generate a (nice looking) roadmap?
I'm using internally a simple text list to represent roadmaps. But that's not enough when it comes to present the roadmap to some powerpoint accustomed decision makers.

Do you know of any techniques to generate (nice looking) development roadmaps? How do you produce your roadmaps?

Update: Started a bounty to draw a little more attention.

答:
It is sad that appearances do matter at all, but I'm sure the big management do appreciate easy to understand visualizations. Towards that route, remember to act as if they were 8 year olds and knew nothing. Everything I do turns out ugly, so I can't give you advice on beauty -- but I can say 'dumb it down' as much as possible.

I do not believe there is any specialized application out there to create the perfect looking ready-map roadmaps for you, though Visio may work. I'd recommend PowerPoint and pretending like you were giving the presentation to first graders ;).


问:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development
I m trying to migrate a project initially developed using EF4 to EF6, to take advantage of EF6 transactions management.

The problem I m facing is that the project has been created using the Database First approach, so when I m using code like context.Database.UseTransaction, I m encountering the following error:

```<code>The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
</code>```

This exception triggers inside the OnModelCreating method of my DbContext class.

Any idea ?

Thanks

EDIT:

The thing is that it's legacy code using EDMX with database first approach. I have to implement EF6 transactions inside this project, so it should now be more like a code first pattern.

In addition, here's the context class:

```<code>public class MyContext : BaseDbContext
{
    public MyContext (DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection)
    {
    }
}
</code>```

And the connection string:

```<code>  <add name="CS"
         connectionString="Data Source=MyServ;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework;Enlist=false"
         providerName="System.Data.EntityClient" />
</code>```

I tried setting the providerName to System.Data.SqlClient but it doesn't change anything.

Please note that the original connection string was in the database first format:

```<code><add name="OrderManagement"
     connectionString="metadata=res://*/MyManagementModel.csdl|res://*/MyManagementModel.ssdl|res://*/MyManagementModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
     providerName="System.Data.EntityClient" />
</code>```

If I try to open a connection whilst I keep the connection string in the database first format, I m facing the exception Keyword metadata not supported, and when I put the connection string on the code first format, I m facing the error The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.

答:
You Have to Just Copy Connection String from App.config and Paste it into your Web.config file.

Make Sure your EDMX has updated to latest connection with database.

This works for me.

Body:
I m trying to migrate a project initially developed using EF4 to EF6, to take advantage of EF6 transactions management.

The problem I m facing is that the project has been created using the Database First approach, so when I m using code like context.Database.UseTransaction, I m encountering the following error:

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.

This exception triggers inside the OnModelCreating method of my DbContext class.

Any idea ?

Thanks

EDIT:

The thing is that it's legacy code using EDMX with database first approach. I have to implement EF6 transactions inside this project, so it should now be more like a code first pattern.

In addition, here's the context class:

public class MyContext : BaseDbContext
{
    public MyContext (DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection)
    {
    }
}

And the connection string:

  <add name="CS"
         connectionString="Data Source=MyServ;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework;Enlist=false"
         providerName="System.Data.EntityClient" />

I tried setting the providerName to System.Data.SqlClient but it doesn't change anything.

Please note that the original connection string was in the database first format:

<add name="OrderManagement"
     connectionString="metadata=res://*/MyManagementModel.csdl|res://*/MyManagementModel.ssdl|res://*/MyManagementModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
     providerName="System.Data.EntityClient" />

If I try to open a connection whilst I keep the connection string in the database first format, I m facing the exception Keyword metadata not supported, and when I put the connection string on the code first format, I m facing the error The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.


问:
Send POST data via raw JSON with Postman
I've got Postman (the one that doesn't open in Chrome) and I'm trying to do a POST request using raw JSON.

In the Body tab I have "raw" selected and "JSON (application/json)" with this body:

```<code>{
    "foo": "bar"
}
</code>```

For the header I have 1, Content-Type: application/json

On the PHP side I'm just doing print_r($_POST); for now, and I'm getting an empty array.

If I use jQuery and do:

```<code>$.ajax({
    "type": "POST",
    "url": "/rest/index.php",
    "data": {
        "foo": "bar"
    }
}).done(function (d) {
    console.log(d);
});
</code>```

I'm getting as expected:

```<code>Array
(
    [foo] => bar
)
</code>```

So why isn't it working with Postman?

Postman screenshots:

and header:

答:
I was facing the same problem, following code worked for me:

```<code>$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got Postman (the one that doesn't open in Chrome) and I'm trying to do a POST request using raw JSON.

In the Body tab I have "raw" selected and "JSON (application/json)" with this body:

{
    "foo": "bar"
}

For the header I have 1, Content-Type: application/json

On the PHP side I'm just doing print_r($_POST); for now, and I'm getting an empty array.

If I use jQuery and do:

$.ajax({
    "type": "POST",
    "url": "/rest/index.php",
    "data": {
        "foo": "bar"
    }
}).done(function (d) {
    console.log(d);
});

I'm getting as expected:

Array
(
    [foo] => bar
)

So why isn't it working with Postman?

Postman screenshots:

and header:

Body:
I was facing the same problem, following code worked for me:

$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);


问:
How change Powered By Liferay
How can i change powered by liferay to custom label and hyperlink when clicking liferay .  I am new to liferay development . Can some suggest to create hook for changing basic functionalities in liferay 7. </p>

答:
You need to write a fragment in Liferay 7

Here is the tutorial
https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-a-modules-jsps

The latest IDE Of Liferay (Released in Dec 2016) provides option to create Liferay fragment hook through IDE.
Previous IDE didnt had the support, other option is you can create through Blade.

Title: How change Powered By Liferay


问:
How to enable visual styles without a manifest
According to the docs:

"If you want your application to use ComCtl32.dll version 6, you must add an application manifest or compiler directive to specify that version 6 should be used if it is available."

Notice the logical OR above? So what is this mysterious compiler directive?

I've got a native Win32 C++ application that is wholly contained in a single .cpp file. There are no resource files, manifest files, etc. I'd like to keep it that way, but I would also like to use visual styles.

答:
If you're using Visual Studio, you can add this line to your stdafx.cpp for example:</p>

```<code>#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

Body:
If you're using Visual Studio, you can add this line to your stdafx.cpp for example:

#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")


问:
Set Azure Reserved IP on cloud service via powershell
as said in the title, I can't assign an IP to my cloud service.

I've followed a lot of forums and StackOverflow articles/posts but I've still the issue.

When I try to run

```<code>Set-AzureReservedIPAssociation -ReservedIPName primosguardo365reservedip -ServiceName primosguardo365
</code>```

I get this error

```<code>Set-AzureReservedIPAssociation : ResourceNotFound: No deployments were found.
At line:1 char:1
+ Set-AzureReservedIPAssociation -ReservedIPName primosguardo365reserve ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzureReservedIPAssociation], CloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.SetAzureReservedIPAssociationCmdlet
</code>```

but if I try to get the resources using the same name

```<code>λ  Get-AzureReservedIP

ReservedIPName       : Group Primosguardo365 primosguardo365reservedip
Address              : **.**.**.**
Id                   : ******************
Label                :
Location             : West Europe
State                : Created
InUse                : False
ServiceName          :
DeploymentName       :
VirtualIPName        :
OperationDescription : Get-AzureReservedIP
OperationId          : ************************
OperationStatus      : Succeeded

λ  Get-AzureService "primosguardo365"

ServiceName             : primosguardo365
Url                     : https://management.core.windows.net.................
Label                   : primosguardo365
Description             : primosguardo365
Location                : West Europe
AffinityGroup           :
Status                  : Created
ExtendedProperties      : {[ResourceGroup, Primosguardo365], [ResourceLocation, westeurope], [ProvisioningSource,
                          AzureResourceManager]}
DateModified            : 28/03/2017 12:13:20
DateCreated             : 28/03/2017 11:26:03
ReverseDnsFqdn          :
WebWorkerRoleSizes      : {}
VirtualMachineRoleSizes : {}
OperationDescription    : Get-AzureService
OperationId             : ****************************
OperationStatus         : Succeeded
</code>```

Does anyone have any suggestion?

Thanks in advance!

EDIT:

VIP can only be assigned to a deployed PRODUCTION instance.

But that's useless, cause CloudServices already have static IP.

Thanks to all!

答:
In my test, I reproduce your error, I just create a cloud service via new portal, and then associate a reserved IP address to it, the error occur.

```<code>PS C:\Users> Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jasontest323"
Set-AzureReservedIPAssociation : ResourceNotFound: No deployments were found.
At line:1 char:1
+ Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jaso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzureReservedIPAssociation], CloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.SetAzureReservedIPAssociationCmdlet
</code>```

After that, I create another cloud service and a VM, then assiscate a reserved IP address to this cloud service, it works.

```<code>PS C:\Users> Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jasonvm3659"

OperationDescription           OperationId                          OperationStatus
--------------------           -----------                          ---------------
Set-AzureReservedIPAssociation 05ccff35-5642-7cc6-9c6b-b5dfe2d1603d Succeeded
</code>```

So, I check the status of the two cloud service, I find when the Production is running, the command will work.

We can use PowerShell to check the deployment:

```<code>PS C:\Users> Get-AzureDeployment -ServiceName jasontest323
Get-AzureDeployment : ResourceNotFound: No deployments were found.
OperationID : '27da300bc3c67a5bbdbc954c1c19e3e7'
At line:1 char:1
+ Get-AzureDeployment -ServiceName jasontest323
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureDeployment], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.GetAzureDeploymentCommand

PS C:\Users> Get-AzureDeployment -ServiceName jasonvm3659

SdkVersion                :
RollbackAllowed           : False
Slot                      : Production
Name                      : jasonvm3659
DeploymentName            : jasonvm3659
Url                       : http://jasonvm3659.cloudapp.net/
Status                    : Running
CurrentUpgradeDomain      : 0
CurrentUpgradeDomainState :
UpgradeType               :
RoleInstanceList          : {jasonvm}
Configuration             : <ServiceConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                            xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
                              <Role name="jasonvm">
                                <Instances count="1" />
                              </Role>
                            </ServiceConfiguration>
DeploymentId              : fc627acb502a4a979b08c42f69cccf72
Label                     : jasonvm3659
VNetName                  : Group jasontest321 jasontest321
DnsSettings               :
OSVersion                 :
RolesConfiguration        : {[jasonvm, Microsoft.WindowsAzure.Commands.ServiceManagement.Model.RoleConfiguration]}
VirtualIPs                : {jasonvm3659ContractContract}
ReservedIPName            : my9
CreatedTime               : 3/29/2017 1:10:28 PM
LastModifiedTime          : 3/29/2017 1:27:42 PM
Locked                    : False
InternalLoadBalancerName  :
LoadBalancers             : {}
ExtensionConfiguration    :
ServiceName               : jasonvm3659
OperationDescription      : Get-AzureDeployment
OperationId               : f8b8xxxx-xxxx-xxxx-xxxx-xxxx2cdc1daa
OperationStatus           : Succeeded
</code>```

The reserved IPs work for classic module, only be used for VMs and cloud service instance roles exposed through a VIP.

So we should check the deployment with powershell Get-AzureDeployment -ServiceName primosguardo365  first.

Body:
as said in the title, I can't assign an IP to my cloud service.

I've followed a lot of forums and StackOverflow articles/posts but I've still the issue.

When I try to run

Set-AzureReservedIPAssociation -ReservedIPName primosguardo365reservedip -ServiceName primosguardo365

I get this error

Set-AzureReservedIPAssociation : ResourceNotFound: No deployments were found.
At line:1 char:1
+ Set-AzureReservedIPAssociation -ReservedIPName primosguardo365reserve ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzureReservedIPAssociation], CloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.SetAzureReservedIPAssociationCmdlet

but if I try to get the resources using the same name

λ  Get-AzureReservedIP

ReservedIPName       : Group Primosguardo365 primosguardo365reservedip
Address              : **.**.**.**
Id                   : ******************
Label                :
Location             : West Europe
State                : Created
InUse                : False
ServiceName          :
DeploymentName       :
VirtualIPName        :
OperationDescription : Get-AzureReservedIP
OperationId          : ************************
OperationStatus      : Succeeded

λ  Get-AzureService "primosguardo365"

ServiceName             : primosguardo365
Url                     : https://management.core.windows.net.................
Label                   : primosguardo365
Description             : primosguardo365
Location                : West Europe
AffinityGroup           :
Status                  : Created
ExtendedProperties      : {[ResourceGroup, Primosguardo365], [ResourceLocation, westeurope], [ProvisioningSource,
                          AzureResourceManager]}
DateModified            : 28/03/2017 12:13:20
DateCreated             : 28/03/2017 11:26:03
ReverseDnsFqdn          :
WebWorkerRoleSizes      : {}
VirtualMachineRoleSizes : {}
OperationDescription    : Get-AzureService
OperationId             : ****************************
OperationStatus         : Succeeded

Does anyone have any suggestion?

Thanks in advance!

EDIT:

VIP can only be assigned to a deployed PRODUCTION instance.

But that's useless, cause CloudServices already have static IP.

Thanks to all!

Body:
In my test, I reproduce your error, I just create a cloud service via new portal, and then associate a reserved IP address to it, the error occur.

PS C:\Users> Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jasontest323"
Set-AzureReservedIPAssociation : ResourceNotFound: No deployments were found.
At line:1 char:1
+ Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jaso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzureReservedIPAssociation], CloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.SetAzureReservedIPAssociationCmdlet

After that, I create another cloud service and a VM, then assiscate a reserved IP address to this cloud service, it works.

PS C:\Users> Set-AzureReservedIPAssociation -ReservedIPName my9 -ServiceName "jasonvm3659"

OperationDescription           OperationId                          OperationStatus
--------------------           -----------                          ---------------
Set-AzureReservedIPAssociation 05ccff35-5642-7cc6-9c6b-b5dfe2d1603d Succeeded

So, I check the status of the two cloud service, I find when the Production is running, the command will work.

We can use PowerShell to check the deployment:

PS C:\Users> Get-AzureDeployment -ServiceName jasontest323
Get-AzureDeployment : ResourceNotFound: No deployments were found.
OperationID : '27da300bc3c67a5bbdbc954c1c19e3e7'
At line:1 char:1
+ Get-AzureDeployment -ServiceName jasontest323
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureDeployment], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.GetAzureDeploymentCommand

PS C:\Users> Get-AzureDeployment -ServiceName jasonvm3659

SdkVersion                :
RollbackAllowed           : False
Slot                      : Production
Name                      : jasonvm3659
DeploymentName            : jasonvm3659
Url                       : http://jasonvm3659.cloudapp.net/
Status                    : Running
CurrentUpgradeDomain      : 0
CurrentUpgradeDomainState :
UpgradeType               :
RoleInstanceList          : {jasonvm}
Configuration             : <ServiceConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                            xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
                              <Role name="jasonvm">
                                <Instances count="1" />
                              </Role>
                            </ServiceConfiguration>
DeploymentId              : fc627acb502a4a979b08c42f69cccf72
Label                     : jasonvm3659
VNetName                  : Group jasontest321 jasontest321
DnsSettings               :
OSVersion                 :
RolesConfiguration        : {[jasonvm, Microsoft.WindowsAzure.Commands.ServiceManagement.Model.RoleConfiguration]}
VirtualIPs                : {jasonvm3659ContractContract}
ReservedIPName            : my9
CreatedTime               : 3/29/2017 1:10:28 PM
LastModifiedTime          : 3/29/2017 1:27:42 PM
Locked                    : False
InternalLoadBalancerName  :
LoadBalancers             : {}
ExtensionConfiguration    :
ServiceName               : jasonvm3659
OperationDescription      : Get-AzureDeployment
OperationId               : f8b8xxxx-xxxx-xxxx-xxxx-xxxx2cdc1daa
OperationStatus           : Succeeded

The reserved IPs work for classic module, only be used for VMs and cloud service instance roles exposed through a VIP.

So we should check the deployment with powershell Get-AzureDeployment -ServiceName primosguardo365  first.


问:
How to display a ForeignKey field as a selection field in django template
I need to display a foreignKey field as a selection field in Django template, which will show all the available records as a dropdown. On considering the case of querying to database every time on selecting the field, which is the best method to achieve above goal to make a selection field from ForeignKey field.</p>

答:
You should use first views to get that foreign key field and pass it over the context dict. to the template.

Inside Views.py

```<code>DEPENDENT_FILED = DB.OBJECT.ALL() // field which has all the drop-down values.
FR_FIELD = DB.OBJECT.GET(DB_OBJ_HAVING_FR) // selected drop-down from template

context['FR_FIELD'] = FR_FIELD
</code>```

Inside example.html

```<code>{% if FR_FIELD %}
    <select name="dropdown_field">
          {%for fr_key in DEPENDENT_FILED %}
               <option value="{{fr_key.field_name}}" {% if fr_key.field_name = FR_FIELD|add:0 %}selected{% endif %}>{{fr_key.option_name}}</option>
         {% endfor %}
    </select>
</code>```

Body:
You should use first views to get that foreign key field and pass it over the context dict. to the template.

Inside Views.py

DEPENDENT_FILED = DB.OBJECT.ALL() // field which has all the drop-down values.
FR_FIELD = DB.OBJECT.GET(DB_OBJ_HAVING_FR) // selected drop-down from template

context['FR_FIELD'] = FR_FIELD

Inside example.html

{% if FR_FIELD %}
    <select name="dropdown_field">
          {%for fr_key in DEPENDENT_FILED %}
               <option value="{{fr_key.field_name}}" {% if fr_key.field_name = FR_FIELD|add:0 %}selected{% endif %}>{{fr_key.option_name}}</option>
         {% endfor %}
    </select>


问:
Time Elapsed Calculation from form in JavaScript
I'm working on a time elapsed calculator were the user enters in a month, day, and year. From their input and the current date, I want to calculate how many days are in between and then display how many years, months, and days have elapsed. I started by making a form with three input values of "month" , "day" , and "year". I then started on the script:

```<code>function timeElapsed() {
       var timeMonth = document.getElementById("month");
       var timeDay = document.getElementById("day");
       var timeYear = document.getElementById("year");
       var currentDate = new Date();
       var elapsed =
       document.getElementById("timeElapsed").innerHTML = elapsed;
   }
       //Event Listener
       var submitButton= document.getElementById("sButton");
    if (submitButton.addEventListener) {
        submitButton.addEventListener("click", timeElapsed, false);
    } else if (submitButton.attachEvent) {
        submitButton.attachEvent("onclick", timeElapsed);
    }
</code>```

Obviously as you can tell I kind of stopped because I'm stumped on where to go from here. This is a lab in school for me and I just want to understand how to do it. My teacher mentioned "Note that your program must include code to convert day values in excess of 31 into months, and months in excess of 12 into years." and I am actually totally confused but understands what he means. It's just actually understanding how to actually do this. It's a web class and it is very hard to understand from just a textbook. I've looked a bit online but I haven't found anything that was useful for my situation. If you can help me out, thank you so much.

答:
In javascript you can get current date as

```<code>var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1; // as it starts from 0
var currentDay = currentDate.getDate();
var currentYear = currentDate.getFullYear();
</code>```

After getting values from your input date fields you need to do some basic mathematical operations like

```<code>if(currentMonth < inputMonth) {
  monthBetween = inputMonth - currentMonth;
} else if(currentMonth > inputMonth) {
  monthBetween = currentMonth - inputMonth;
} else {
  monthBetween = 0;
}
</code>```

Here is some sample code you can play around and learn from. https://jsfiddle.net/8pd5f3pe/1/

Body:
I'm working on a time elapsed calculator were the user enters in a month, day, and year. From their input and the current date, I want to calculate how many days are in between and then display how many years, months, and days have elapsed. I started by making a form with three input values of "month" , "day" , and "year". I then started on the script:

function timeElapsed() {
       var timeMonth = document.getElementById("month");
       var timeDay = document.getElementById("day");
       var timeYear = document.getElementById("year");
       var currentDate = new Date();
       var elapsed =
       document.getElementById("timeElapsed").innerHTML = elapsed;
   }
       //Event Listener
       var submitButton= document.getElementById("sButton");
    if (submitButton.addEventListener) {
        submitButton.addEventListener("click", timeElapsed, false);
    } else if (submitButton.attachEvent) {
        submitButton.attachEvent("onclick", timeElapsed);
    }

Obviously as you can tell I kind of stopped because I'm stumped on where to go from here. This is a lab in school for me and I just want to understand how to do it. My teacher mentioned "Note that your program must include code to convert day values in excess of 31 into months, and months in excess of 12 into years." and I am actually totally confused but understands what he means. It's just actually understanding how to actually do this. It's a web class and it is very hard to understand from just a textbook. I've looked a bit online but I haven't found anything that was useful for my situation. If you can help me out, thank you so much.

Body:
In javascript you can get current date as

var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1; // as it starts from 0
var currentDay = currentDate.getDate();
var currentYear = currentDate.getFullYear();

After getting values from your input date fields you need to do some basic mathematical operations like

if(currentMonth < inputMonth) {
  monthBetween = inputMonth - currentMonth;
} else if(currentMonth > inputMonth) {
  monthBetween = currentMonth - inputMonth;
} else {
  monthBetween = 0;
}

Here is some sample code you can play around and learn from. https://jsfiddle.net/8pd5f3pe/1/


问:
Contour segmentation
I have a contour which consists of curved segments and straigth segments. Is there any possibility to segment the contour into the curved and straigth parts?
So this is an example for a contour

I would like to have a segmentation like this:

Do you have any idea how I could solve such a problem

Thank you very much and best regards

答:
This is my contour

And this is the result of segmentation

Title: Contour segmentation


问:
Ruby - Sum of pairs in an array that add to a certain given input
I'm doing a ruby problem and my solution works. However, it does not work on bigger test cases because it takes too long to process.

The method takes two inputs, an array of numbers and a number.

The goal is to find the first two numbers in the array whose sum is the number provided in the input.

The first pair means that the highest index of the pair is lower than the highest index of any other pairs in the array that add to the number.

Example - ([10, 5, 2, 3, 7, 5], 10)

The answer should be [3, 7] while [5, 5] also sums to 10, the index of the last 5 is 5 and the index of 7 is 4, so [3, 7] comes first.

```<code>def sum_pairs(ints, s)
  return nil if ints.empty? || ints.nil?

  x = ints.combination(2).select {|x, y| x + y == s}

  return nil if x.nil? || x.empty?

  ints.rindex(x[0][1]) > ints.rindex(x[-1][1]) ? x.last : x.first

end
</code>```

My code worked for all test cases besides those with large arrays.

I was wondering if there was a built in method to help or if I needed to loop through the array differently.

答:
An alternative approach might be to make sure your combinations are always in the correct order of preference, and then use #find instead of #select. The standard Ruby #combination(2) pairs element 0 with all later elements ([10,5],[10,2],[10,3],[10,7],[10,5]) then pairs index 1 with all later elements ([5,2],[5,3],[5,7],[5,5]) and so forth.

You could write a new modified_combination method that pairs element 1 with all earlier elements ([5,10]) then pairs element 2 with all earlier elements ([2,10],[2,5]), then element 3 ([3,10],[3,5],[3,2]) and so forth. This will ensure the pair with the smallest larger index number is always first in the list.

Now you can do:

```<code>x = ints.modified_combination.find { |x, y| x, y == s }.reverse
</code>```

Remember, this will work most efficiently if modified_combination returns an Enumerator rather than an Array (though it will be much more efficient than your original approach in any case).

If you don't want to dig into creating a method that returns an Enumerator, here's a quick-and-dirty solution that achieves the same thing:

```<code>def sum_pairs(ints, s)
  (1...ints.size).each do |x|
    (0...x).each do |y|
      return [ints[y], ints[x]] if ints[x] + ints[y] == s
    end
  end
  nil
end
</code>```

Body:
I'm doing a ruby problem and my solution works. However, it does not work on bigger test cases because it takes too long to process.

The method takes two inputs, an array of numbers and a number.

The goal is to find the first two numbers in the array whose sum is the number provided in the input.

The first pair means that the highest index of the pair is lower than the highest index of any other pairs in the array that add to the number.

Example - ([10, 5, 2, 3, 7, 5], 10)

The answer should be [3, 7] while [5, 5] also sums to 10, the index of the last 5 is 5 and the index of 7 is 4, so [3, 7] comes first.

def sum_pairs(ints, s)
  return nil if ints.empty? || ints.nil?

  x = ints.combination(2).select {|x, y| x + y == s}

  return nil if x.nil? || x.empty?

  ints.rindex(x[0][1]) > ints.rindex(x[-1][1]) ? x.last : x.first

end

My code worked for all test cases besides those with large arrays.

I was wondering if there was a built in method to help or if I needed to loop through the array differently.

Body:
An alternative approach might be to make sure your combinations are always in the correct order of preference, and then use #find instead of #select. The standard Ruby #combination(2) pairs element 0 with all later elements ([10,5],[10,2],[10,3],[10,7],[10,5]) then pairs index 1 with all later elements ([5,2],[5,3],[5,7],[5,5]) and so forth.

You could write a new modified_combination method that pairs element 1 with all earlier elements ([5,10]) then pairs element 2 with all earlier elements ([2,10],[2,5]), then element 3 ([3,10],[3,5],[3,2]) and so forth. This will ensure the pair with the smallest larger index number is always first in the list.

Now you can do:

x = ints.modified_combination.find { |x, y| x, y == s }.reverse

Remember, this will work most efficiently if modified_combination returns an Enumerator rather than an Array (though it will be much more efficient than your original approach in any case).

If you don't want to dig into creating a method that returns an Enumerator, here's a quick-and-dirty solution that achieves the same thing:

def sum_pairs(ints, s)
  (1...ints.size).each do |x|
    (0...x).each do |y|
      return [ints[y], ints[x]] if ints[x] + ints[y] == s
    end
  end
  nil
end


问:
Adding 2 components in my app.component.ts
In my app.component I would like to display 2 different components. One is a list of courses the other a list of authors.

I ended up with below, individually they work, so coursescomponent commented out the authors component will display.

How do I get both to display?

```<code>import {Component} from 'angular2/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'

@Component({
selector: 'my-app',
template: '<h1>My first Angular2 App</h1><courses></courses>',
directives: [CoursesComponent],

})

@Component({
selector: 'my-app',

template: '<authors></authors>',
directives: [AuthorsComponent]

})
export class AppComponent { }
</code>```

答:
do this:

```<code>import {Component} from 'angular2/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'

@Component({
  selector: 'my-app',
  template: '<h1>My first Angular2 App</h1><courses></courses> <authors></authors>',
  directives: [CoursesComponent, AuthorsComponent],
})

export class AppComponent { }
</code>```

btw, update your code based-on latest Angular version as this tutorial

https://angular.io/docs/ts/latest/guide/learning-angular.html

include your directives, pipe and other components to declarations array.

src/app/app.module.ts

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent/* other pipe, directive, component */ ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

Body:
In my app.component I would like to display 2 different components. One is a list of courses the other a list of authors.

I ended up with below, individually they work, so coursescomponent commented out the authors component will display.

How do I get both to display?

import {Component} from 'angular2/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'

@Component({
selector: 'my-app',
template: '
My first Angular2 App
<courses></courses>',
directives: [CoursesComponent],

})

@Component({
selector: 'my-app',

template: '<authors></authors>',
directives: [AuthorsComponent]

})
export class AppComponent { }

Body:
do this:

import {Component} from 'angular2/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'

@Component({
  selector: 'my-app',
  template: '<h1>My first Angular2 App</h1><courses></courses> <authors></authors>',
  directives: [CoursesComponent, AuthorsComponent],
})

export class AppComponent { }

btw, update your code based-on latest Angular version as this tutorial

https://angular.io/docs/ts/latest/guide/learning-angular.html

include your directives, pipe and other components to declarations array.

src/app/app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent/* other pipe, directive, component */ ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }


问:
How to autogenerate ids Using annotations in Hibernate?
I want to create table of product in which i can save product id as primary key , and second table there is category table in this table there is the catid as primary key,but  problem is both Generate  Key In Fashion of 1,2,3,4 mans both have Same column ,How to generate key likes PID001,PI002..... and CATID001 ,CATID002

答:
In this case you should use custom id generator strategy.

For Custom Id generation we need to implement IdentifierGenerator interface and need to provide the body of generate method.

IdentifierGenerator have method generate so you need to provide the body of it.

Here is an example of custom id  generator strategy.


问:
Hover button that shows text html/css
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

```<code><title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
    /*TEST HERE*/
    .w3-button {width:800px;}
    .w3-button {height:800px;} `
</style>
<div class="w3-container">
    <h2>TITULO AQUI</h2>
    <p>
        <button class="w3-button w3-light-blue">Hover in here</button>
    </p>
</div>
/*<div id="button1"></div>*/
</code>```

答:
Title is the easiest not very pretty solution...

Other way is to have hidden child tooltip element showing only on hover.

div {
  border: 1px solid;
  padding: 2px;
  position: relative;
  display: inline-block;
}

.tooltip {
  opacity: 0;
  pointer-events: none;
  position: absolute;
  left: 100%;
  width: 150px;
  transition: opacity .5s;
  padding: 1px;
  margin: 0 2px;
  top: 0;
  border: 1px solid #000;
  background: rgba(0, 0, 0, .7);
  color: #FFF;
}

.hoverTooltip:hover .tooltip {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div title='Here is "native" tooltip'>"native" tooltip via title</div>
<br /><br />
<div class="hoverTooltip">
  hover element tooltip
  <span class="tooltip">Here is your custom styled tooltip</span>
</div></code>```

Title: Hover button that shows text html/css

Body:
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

TITULO AQUI

        <button class="w3-button w3-light-blue">Hover in here</button>

/*

*/

Body:
Title is the easiest not very pretty solution...

Other way is to have hidden child tooltip element showing only on hover.

div {
  border: 1px solid;
  padding: 2px;
  position: relative;
  display: inline-block;
}

.tooltip {
  opacity: 0;
  pointer-events: none;
  position: absolute;
  left: 100%;
  width: 150px;
  transition: opacity .5s;
  padding: 1px;
  margin: 0 2px;
  top: 0;
  border: 1px solid #000;
  background: rgba(0, 0, 0, .7);
  color: #FFF;
}

.hoverTooltip:hover .tooltip {
  opacity: 1;
}

<div title='Here is "native" tooltip'>"native" tooltip via title</div>
<br /><br />
<div class="hoverTooltip">
  hover element tooltip
  <span class="tooltip">Here is your custom styled tooltip</span>
</div>


问:
Comparing two arrays with array_diff
I have the following code and am trying to compare two array's with array_diff however I keep getting no results. I not sure if it matters, but there are many fields in the array and I really only want to compare 1 field...is this possible? what am I missing?</p>

```<code><?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");

$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);

if ( $array1 == $array2 ) {
echo 'There are no differences';
}else
var_dump(array_diff($array2, $array1));
echo 'they are different';

?>
</code>```

答:
```<code>    $po_line_array=array();
    $po_line_clone_array=array();

    foreach($cart->line_items as $line_no => $po_line)
         $po_line_array[$line_no]=$po_line->labdip_details_id;
       print_r($po_line_array,1);
    foreach($cart->line_items_clone as $line_no_clone => $po_line_clone)
         $po_line_clone_array[$line_no_clone]=$po_line_clone->labdip_details_id;
       print_r($po_line_clone_array,1);

     $result=array_diff($po_line_clone_array,$po_line_array);
     print_r($result,1);
</code>```

Output:

```<code> Array ( [0] => 101 )

    Array ( [0] => 101 [1] => 103 )

    Array ( [1] => 103 )
</code>```

Title: Comparing two arrays with array_diff

Body:
I have the following code and am trying to compare two array's with array_diff however I keep getting no results. I not sure if it matters, but there are many fields in the array and I really only want to compare 1 field...is this possible? what am I missing?

<?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");

$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);

if ( $array1 == $array2 ) {
echo 'There are no differences';
}else
var_dump(array_diff($array2, $array1));
echo 'they are different';

?>

Body:
    $po_line_array=array();
    $po_line_clone_array=array();

    foreach($cart->line_items as $line_no => $po_line)
         $po_line_array[$line_no]=$po_line->labdip_details_id;
       print_r($po_line_array,1);
    foreach($cart->line_items_clone as $line_no_clone => $po_line_clone)
         $po_line_clone_array[$line_no_clone]=$po_line_clone->labdip_details_id;
       print_r($po_line_clone_array,1);

     $result=array_diff($po_line_clone_array,$po_line_array);
     print_r($result,1);

Output:

 Array ( [0] => 101 )

    Array ( [0] => 101 [1] => 103 )

    Array ( [1] => 103 )


问:
How to JOIN with ON CASE in Codeigniter
I want to use CASE in JOIN condition, but it's not working anymore.

```<code>$this->db->join('user_profile ON sender.user_id = CASE WHEN mailbox.sender_user_id = 1
                             THEN mailbox_recipient.recipient_user_id
                             ELSE mailbox.sender_user_id END');
</code>```

Showing ERROR like this

```<code>JOIN `user_profile ON sender`.`user_id = CASE WHEN mailbox`.`sender_user_id = 1 THEN mailbox_recipient`.`recipient_user_id ELSE mailbox`.`sender_user_id` `END`
</code>```

a single quote ``` disorganized

答:
I try to use other alternatives,

```<code>$this->db->join('user_profile AS sender', 'sender.user_id = '.$this->table_name.'.sender_user_id');
$this->db->join('user_profile AS recipient', 'recipient.user_id = '.$this->table_name.'_recipient.recipient_user_id');
</code>```

then in my SELECT like this :

```<code>$this->db->select(
      $this->table_name.'.*,
      (CASE WHEN mailbox.sender_user_id = '.$this->user_id.' THEN recipient.fullname ELSE sender.fullname END) AS user_name');
</code>```

Title: How to JOIN with ON CASE in Codeigniter

Body:
I want to use CASE in JOIN condition, but it's not working anymore.

$this->db->join('user_profile ON sender.user_id = CASE WHEN mailbox.sender_user_id = 1
                             THEN mailbox_recipient.recipient_user_id
                             ELSE mailbox.sender_user_id END');

Showing ERROR like this

JOIN `user_profile ON sender`.`user_id = CASE WHEN mailbox`.`sender_user_id = 1 THEN mailbox_recipient`.`recipient_user_id ELSE mailbox`.`sender_user_id` `END`

a single quote ``` disorganized

Body:
I try to use other alternatives,

$this->db->join('user_profile AS sender', 'sender.user_id = '.$this->table_name.'.sender_user_id');
$this->db->join('user_profile AS recipient', 'recipient.user_id = '.$this->table_name.'_recipient.recipient_user_id');

then in my SELECT like this :

$this->db->select(
      $this->table_name.'.*,
      (CASE WHEN mailbox.sender_user_id = '.$this->user_id.' THEN recipient.fullname ELSE sender.fullname END) AS user_name');


问:
SharePoint -integrating CKEditor
I am needing to replace the default HTML editor that comes with WSS 3.0 by CKEditor to edit web parts.

I read about adding a new content type but I am working on a limited shared host.

Thank you very much for your help.

答:
I know this question is 4 months old, but for anyone looking for an answer, here it is: CKEditor for SharePoint

Easy to install and upgrade, compatible with SharePoint 2007 and SharePoint 2010. CKFinder is included.

Fully functional 30 days trial version is available.

Title: SharePoint -integrating CKEditor


问:
ESP8266 Arduino 2.2 TFT ILI9341
I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.

This is the one.TTT ILI9341

I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino. (https://github.com/esp8266/Arduino)

I made the following connection :

I made the following connection : SCK #14, MOSI #13, MISO #12 and CS, #4, DC #5,RESET #0

and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds. In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .

In my existing project, I used the following code to just show some messages :

```<code>Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);
</code>```

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.

I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.

I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.

Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.

Thanks in advance. !!!

答:
Also, you can try using delay() or yield() functions in between.
The esp8266 may restart itself due to the watchdog when a loop a takes long time to process.</p>

Title: ESP8266 Arduino 2.2 TFT ILI9341

Body:
I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.

This is the one.TTT ILI9341

I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino. (https://github.com/esp8266/Arduino)

I made the following connection :

I made the following connection : SCK #14, MOSI #13, MISO #12 and CS, #4, DC #5,RESET #0

and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds. In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .

In my existing project, I used the following code to just show some messages :

Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.

I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.

I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.

Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.

Thanks in advance. !!!


问:
default input border shows differently on div
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

```

Why is that ? and what kind of border will give me the same one as the input ?

答:
OK fount it

input has the -webkit-appearance:textfield; style on it

div {
  border: 2px inset;
  -webkit-appearance: textfield;
  height: 15px;
  width: 169px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input>
<br><br>
<div></div></code>```

Body:
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

Why is that ? and what kind of border will give me the same one as the input ?

Body:
OK fount it

input has the -webkit-appearance:textfield; style on it

div {
  border: 2px inset;
  -webkit-appearance: textfield;
  height: 15px;
  width: 169px;
}

<input>
<br><br>
<div></div>


问:
Command to delete an entire method?
I am using viemu in VS 2010. Is there a reliable command to delete an entire method in C# source code?

Here are things I have tried:

The movement commands } and ]] are not smart enough to pick out a method. Although at times they do happen to grab the correct amount of text.

From just within the method i can do diB which will delete the entire body of the method. That's not too bad, but then I'm left to delete the signature and outer brackets.

If I move the cursor to the visibility modifier (ie public, private, etc) then do d*, it will kill the entire method if the next method has the same visibility.

Any vi/viemu experts have a way to do this?

答: dap (delete a paragraph) will work for simple methods which do not contain empty lines. For methods which do contain empty lines you will need to use diBdap (delete inner block followed by delete a paragraph). For easier use you can create a mapping in your rc file. ex: :nmap <C-d> diBdap

Title: Command to delete an entire method?