问:
Double iteration to a list python 3
```<code>for x in range(0,img_row):
    for y in range(0,img_col):
       img_lst.append([img[x,y][0],img[x,y][1],img[x,y][2]])
return img_lst
</code>```

How do I use list Comprehension here?

```<code>img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
</code>```

I tried this but it is giving my invalid syntax and when I remove "y" in the beginning it gives me that Y is not defined

the whole function:

```<code>def cvimg_to_list(img):
    img_row = img.shape[0]
    img_col = img.shape[1]
    img_lst=[]

    img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
    return img_lst
</code>```

答:
I'm not totally sure about what are you trying to achieve, but if my assumption is correct (you want to get a list of pixel values values from the three channels of an image that you opened with opencv), you can use numpy to do this.

```<code>img_lst=img.reshape(-1,3).tolist()
</code>```

Bearing in mind that cv2 loads images as BGR and not RGB.

note: not being properly an answer to the question, I would have rather post this as a comment but I don't have enough reputation for that

Title: Double iteration to a list python 3

Body:
for x in range(0,img_row):
    for y in range(0,img_col):
       img_lst.append([img[x,y][0],img[x,y][1],img[x,y][2]])
return img_lst

How do I use list Comprehension here?

img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]

I tried this but it is giving my invalid syntax and when I remove "y" in the beginning it gives me that Y is not defined

the whole function:

def cvimg_to_list(img):
    img_row = img.shape[0]
    img_col = img.shape[1]
    img_lst=[]

    img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
    return img_lst

Body:
I'm not totally sure about what are you trying to achieve, but if my assumption is correct (you want to get a list of pixel values values from the three channels of an image that you opened with opencv), you can use numpy to do this.

img_lst=img.reshape(-1,3).tolist()

Bearing in mind that cv2 loads images as BGR and not RGB.

note: not being properly an answer to the question, I would have rather post this as a comment but I don't have enough reputation for that


来源: stackexchange

问:
SQL to select and swap id columns so parameter appears in left hand column
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1
</code>```

Desired output if I'm looking for value 1, note the last two columns switching position:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5
</code>```

My current SQL is as follows:

```<code>SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);
</code>```

Which gets the correct values, but without swapping. The result is:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
</code>```

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

答:
Something like this:</p>

```<code>select 1 as id1,
       (case when id1 = 1 then id2 else id1 end) as id2,
       value
from t
where 1 in (id1, id2)
order by value;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1

Desired output if I'm looking for value 1, note the last two columns switching position:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5

My current SQL is as follows:

SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);

Which gets the correct values, but without swapping. The result is:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

Body:
Something like this:

select 1 as id1,
       (case when id1 = 1 then id2 else id1 end) as id2,
       value
from t
where 1 in (id1, id2)
order by value;


问:
Mapping JSON to Class automatically - design issue
I am using a certain API which returns JSON data in the following format:

```<code>entities {
    entity#1 { [property#1:value, property#2:value] },
    entity#2 { [property#3:value, property#4:value] }
}
</code>```

The entities in this JSON are defined manually, which means each entity can have unique properties. What is the best way to parse this kind of data?

At the moment, I'm making a unique class for each entity that I define on the API however the amount of entities that I define could be well over 100.

Is there a way in Java to create a single class that would have the shared properties pre-defined, and then add properties to that same class on runtime?

答:
Your entities probably share some of the common properties and differ in others. It that case a decent compromise approach would be having a class containing the common properties as class fields. The rest needs to be stored in a Map a  key-value pairs. This allows you to have at least some class structure without having a hundred of slightly different classes.

Something like

```<code>private String someProperty;
private boolean someOtherCommonProperty;
...

private Map<String, Object> allTheOtherProperties;
</code>```

For deserialization details check this article:
http://www.baeldung.com/jackson-map

Specifically 4.2. Map Deserialization

Body:
I am using a certain API which returns JSON data in the following format:

entities {
    entity#1 { [property#1:value, property#2:value] },
    entity#2 { [property#3:value, property#4:value] }
}

The entities in this JSON are defined manually, which means each entity can have unique properties. What is the best way to parse this kind of data?

At the moment, I'm making a unique class for each entity that I define on the API however the amount of entities that I define could be well over 100.

Is there a way in Java to create a single class that would have the shared properties pre-defined, and then add properties to that same class on runtime?

Body:
Your entities probably share some of the common properties and differ in others. It that case a decent compromise approach would be having a class containing the common properties as class fields. The rest needs to be stored in a Map a  key-value pairs. This allows you to have at least some class structure without having a hundred of slightly different classes.

Something like

private String someProperty;
private boolean someOtherCommonProperty;
...

private Map<String, Object> allTheOtherProperties;

For deserialization details check this article:
http://www.baeldung.com/jackson-map

Specifically 4.2. Map Deserialization


问:
Not able to drag a formula calculating days
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")
</code>```

So if i drag i should get the below formulea which i am not getting.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")
</code>```

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.

答:
One way is to set up a static index of 1-7 and make the formula refer to that - this will make the reference update as you drag it along the columns:

So, per this example:

The formula is:

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,E$1),1),"aaa")
</code>```

Body:
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")

So if i drag i should get the below formulea which i am not getting.

=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.

Body:
One way is to set up a static index of 1-7 and make the formula refer to that - this will make the reference update as you drag it along the columns:

So, per this example:

The formula is:

=TEXT(WEEKDAY(DATE(CurrentYear,1,E$1),1),"aaa")


问:
C++ how to infer the Callable's type (arguments list & return value) in a template
Basically what I want to do, is to make a function template, that takes any Callable (function type / lambda / Functor) and returns a lambda-taking-the-similar-args-list and returning the type of original's return type</p>

```<code>#include <iostream>

int func(int a,float b) {
    return a+b;
}

struct callable {
    int operator() (int a, float b) {
        return a+b;
    }
};

template <typename RV, typename... Args>
auto getLambdaFromCallable(RV(&func)(Args...)) {
    auto l = [&](Args... args) -> RV {
        return func(args...);
    };

    return l;
}

int main() {
    auto f = getLambdaFromCallable(func);
    std::cout << f(1,2.f);
    std::cout << " " << typeid(f).name();

    auto f2 = getLambdaFromCallable(callable{}); // doesn't work
    callable{}(1,2); // works

    auto lambdaTest = [](int a, float b) -> int {
        return a+b;
    };
    auto f3 = getLambdaFromCallable(lambdaTest);
}
</code>```

答:
If you can use C++17, std::invoke is the right tool:

```<code>#include <functional>

template <typename OBJ>
auto getLambdaFromCallable(OBJ&& obj)
{
  return [&](const auto&... args) {
                return std::invoke(std::forward<OBJ>(obj), args...);
         };
}
</code>```

You can compile it with g++ -std=c++17 or clang++-5.0 -std=c++1z and this is working out of the box.

Body:
Basically what I want to do, is to make a function template, that takes any Callable (function type / lambda / Functor) and returns a lambda-taking-the-similar-args-list and returning the type of original's return type

#include <iostream>

int func(int a,float b) {
    return a+b;
}

struct callable {
    int operator() (int a, float b) {
        return a+b;
    }
};

template <typename RV, typename... Args>
auto getLambdaFromCallable(RV(&func)(Args...)) {
    auto l = [&](Args... args) -> RV {
        return func(args...);
    };

    return l;
}

int main() {
    auto f = getLambdaFromCallable(func);
    std::cout << f(1,2.f);
    std::cout << " " << typeid(f).name();

    auto f2 = getLambdaFromCallable(callable{}); // doesn't work
    callable{}(1,2); // works

    auto lambdaTest = [](int a, float b) -> int {
        return a+b;
    };
    auto f3 = getLambdaFromCallable(lambdaTest);
}

Body:
If you can use C++17, std::invoke is the right tool:

#include <functional>

template <typename OBJ>
auto getLambdaFromCallable(OBJ&& obj)
{
  return [&](const auto&... args) {
                return std::invoke(std::forward<OBJ>(obj), args...);
         };
}

You can compile it with g++ -std=c++17 or clang++-5.0 -std=c++1z and this is working out of the box.


问:
IIS website physical path becomes blank on wix uninstall
Background: I have a Wix installer where a virtual directory gets created in an existing IIS website. The virtual directory is created (it doesn't exist before the install) but the IIS website should already be created (user just picks a website to install to in a ListBox).

The problem: On uninstall, the Physical Path of the IIS website that got installed to becomes blank, no value for that attribute. Below is a pared down version of my main wix file. I'm not sure why the uninstall is affecting the IIS website, but any thoughts are appreciated.

Notes: I'm on Wix 3.5 and Windows Server 2008 R2, IIS 7.

```<code><Product>

    <Property Id='WEBSITE_DESCRIPTION'>
      <RegistrySearch Id='RememberPropertyWEBSITE_DESCRIPTION' Root='HKCU'
        Key='SOFTWARE\Company\Product' Name='InstalledWebsiteDescription'
        Type='raw' />
    </Property>

    <Property Id='WEBSITE_PORT'>
      <RegistrySearch Id='RememberPropertyWEBSITE_PORT' Root='HKCU'
        Key='SOFTWARE\Company\Product' Name='InstalledWebsitePort'
        Type='raw' />
    </Property>

    <Component Id='PropertiesToSave' Directory='ApplicationFolder'>
      <RegistryValue Root='HKCU' Key='SOFTWARE\Company\Product'
        Name='InstalledWebsiteDescription' Value='[WEBSITE_DESCRIPTION]'
        Type='string' />
      <RegistryValue Root='HKCU' Key='SOFTWARE\Company\Product'
        Name='InstalledWebsitePort' Value='[WEBSITE_PORT]'
        Type='string' />

      <RemoveFolder Id='CleanupApplicationFolder' On='uninstall' />
    </Component>

    <Directory Id='TARGETDIR' Name='SourceDir'>
      <Component Id='TestWebVirtualDirComponent' Guid='12345678-6304-410E-A808-E3585379EADB'>
        <CreateFolder />
        <iis:WebVirtualDir Id='TestWebVirtualDir' Alias='[WEBSITE_VIRTUALDIR]' Directory='TARGETDIR' WebSite='MyWebsite'>
          <iis:WebApplication Id='TestWebApplication' Name='Test' />
        </iis:WebVirtualDir>
      </Component>
    </Directory>

    <iis:WebSite Id="MyWebsite" Description="[WEBSITE_DESCRIPTION]" SiteId="*">
      <iis:WebAddress Id="AllUnassigned" Port="[WEBSITE_PORT]" />
    </iis:WebSite>

    <Feature>
      <ComponentRef Id='TestWebVirtualDirComponent'/>
      <ComponentRef Id='PropertiesToSave'/>
    </Feature>
</Product>
</code>```

答:
WiX IIsExtension recognizes the WebSite by Description attribute and Port attribute of child WebAddress element. So, when you install your application, you set WEBSITE_DESCRIPTION and WEBSITE_PORT in some way. However, when you run uninstall, the mentioned properties are not set, and you get the behavior you described.

The solution to this is to save the required property values to system registry and use RegistrySearch element to read the values and set appropriate properties. This is called "Remember Property" pattern and is perfectly explained by Rob Mensching here.

ContentLicense: CC BY-SA 2.5

Body:
Background: I have a Wix installer where a virtual directory gets created in an existing IIS website. The virtual directory is created (it doesn't exist before the install) but the IIS website should already be created (user just picks a website to install to in a ListBox).

The problem: On uninstall, the Physical Path of the IIS website that got installed to becomes blank, no value for that attribute. Below is a pared down version of my main wix file. I'm not sure why the uninstall is affecting the IIS website, but any thoughts are appreciated.

Notes: I'm on Wix 3.5 and Windows Server 2008 R2, IIS 7.

<Product>

    <Property Id='WEBSITE_DESCRIPTION'>
      <RegistrySearch Id='RememberPropertyWEBSITE_DESCRIPTION' Root='HKCU'
        Key='SOFTWARE\Company\Product' Name='InstalledWebsiteDescription'
        Type='raw' />
    </Property>

    <Property Id='WEBSITE_PORT'>
      <RegistrySearch Id='RememberPropertyWEBSITE_PORT' Root='HKCU'
        Key='SOFTWARE\Company\Product' Name='InstalledWebsitePort'
        Type='raw' />
    </Property>

    <Component Id='PropertiesToSave' Directory='ApplicationFolder'>
      <RegistryValue Root='HKCU' Key='SOFTWARE\Company\Product'
        Name='InstalledWebsiteDescription' Value='[WEBSITE_DESCRIPTION]'
        Type='string' />
      <RegistryValue Root='HKCU' Key='SOFTWARE\Company\Product'
        Name='InstalledWebsitePort' Value='[WEBSITE_PORT]'
        Type='string' />

      <RemoveFolder Id='CleanupApplicationFolder' On='uninstall' />
    </Component>

    <Directory Id='TARGETDIR' Name='SourceDir'>
      <Component Id='TestWebVirtualDirComponent' Guid='12345678-6304-410E-A808-E3585379EADB'>
        <CreateFolder />
        <iis:WebVirtualDir Id='TestWebVirtualDir' Alias='[WEBSITE_VIRTUALDIR]' Directory='TARGETDIR' WebSite='MyWebsite'>
          <iis:WebApplication Id='TestWebApplication' Name='Test' />
        </iis:WebVirtualDir>
      </Component>
    </Directory>

    <iis:WebSite Id="MyWebsite" Description="[WEBSITE_DESCRIPTION]" SiteId="*">
      <iis:WebAddress Id="AllUnassigned" Port="[WEBSITE_PORT]" />
    </iis:WebSite>

    <Feature>
      <ComponentRef Id='TestWebVirtualDirComponent'/>
      <ComponentRef Id='PropertiesToSave'/>
    </Feature>
</Product>


问:
How can i find Indian Accent in TextToSpeech class of Andorid
I cannot find Locale.IN in Android, like Locale.UK, Locale.US.

Where could I find it?

答: I am not Indian, but if you set the language to Locale("hi", "IN") and let the tts speak English phrases they pretty much sound like the way my Indian friends speak. Might not be a perfect Indian accent you are looking for but close enough I think. Similarly if you want to put some "french accent" set the language to Locale("fr", "FR") and and let it speak English phrases. </p>


问:
SELECT QUERY LIKE containing only specific words in a string
I have one table like below ,table name is js_skills_achievements

```<code>id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery
</code>```

When admin search key is "java developer in nersupalli"

my query is below

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10
</code>```

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10
</code>```

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

答:
Other answers are more technical and probably more optimized, however if you wish to have full control on your query, like changing OR to AND and things like this, you can split your query in words and build it manually:</p>

```<code>//your search query
$query = 'java developer in nersupalli';

//in case you want to add more skills later
$skills = ['skill1', 'skill2', 'skill3', 'skill4'];

//split your query in an array of words
$words = explode(' ', $query);

//build the sql
$condOuter = '';
foreach($skills as $skill){
    $condInner = '';
    foreach($words as $word){
        $condInner .= " OR `$skill` LIKE '%$word%'";
    }
    $condInner = substr($condInner, 4);
    $condOuter .= " OR ($condInner)";
}
$condOuter = substr($condOuter, 4);
$sql = 'SELECT * FROM `js_skills_achievements` WHERE ' . $condOuter . ' ORDER BY id DESC LIMIT 10;';
</code>```

Body:
I have one table like below ,table name is js_skills_achievements

id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery

When admin search key is "java developer in nersupalli"

my query is below

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

Body:
Other answers are more technical and probably more optimized, however if you wish to have full control on your query, like changing OR to AND and things like this, you can split your query in words and build it manually:

//your search query
$query = 'java developer in nersupalli';

//in case you want to add more skills later
$skills = ['skill1', 'skill2', 'skill3', 'skill4'];

//split your query in an array of words
$words = explode(' ', $query);

//build the sql
$condOuter = '';
foreach($skills as $skill){
    $condInner = '';
    foreach($words as $word){
        $condInner .= " OR `$skill` LIKE '%$word%'";
    }
    $condInner = substr($condInner, 4);
    $condOuter .= " OR ($condInner)";
}
$condOuter = substr($condOuter, 4);
$sql = 'SELECT * FROM `js_skills_achievements` WHERE ' . $condOuter . ' ORDER BY id DESC LIMIT 10;';


问:
Spring + Jackson: Wrapping Response Body in response object
This may be a strange question, although I wonder why it hasn't been asked or proposed before... so please correct me if any ignorance.

First off, I am using Jackson in conjunction with Spring and the @ResponseBody annotation.
Currently, for every request handler I am returning a "Response" wrapper object, as that is what the client expects. This wrapper is quite simple:

```<code>{ "response": { "data" : ACTUAL_DATA } }
</code>```

Thing is, I'm not a fan of explicitly wrapping each return value for all my request handlers. I also do not like having to unwrap these response wrappers in my unit tests.

Rather, I wonder if it were possible to return the ACTUAL_DATA as it were, and to intercept and wrap this data elsewhere.

If this is in fact possible, would it then be possible to read the annotations attached to the intercepted request handler? This way I can use custom annotations to decide how to wrap the data.

For example something like this would be amazing (note that @FetchResponse and @ResponseWrapper are made up proposed annotations):

```<code>@RequestMapping(...)
@FetchResponse
@ResponseBody
public List<User> getUsers() {
    ...
}

@ResponseWrapper(FetchResponse.class)
public Object wrap(Object value) {
    ResponseWrapper rw = new ResponseWrapper();
    rw.setData(value);
    return rw;
}
</code>```

Anyone familiar with this territory? Or alternatively, and reasons why this might be bad practice?

答:
For anybody looking on more info on this topic: I was facing the same issue as well, and thanks to the tip of kennyg, i managed to come up with the following solution:

```<code>import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class JSendAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof JSendResponse) {
            return body;
        }

        return new JSendResponse<>().success(body);
    }
}
</code>```

This solution wraps all the objects returned in your controllers inside a (for this example) JSendResponse class, which saves you the hassle of returning JSendResponses in all of your controller methods.

Body:
This may be a strange question, although I wonder why it hasn't been asked or proposed before... so please correct me if any ignorance.

First off, I am using Jackson in conjunction with Spring and the @ResponseBody annotation.
Currently, for every request handler I am returning a "Response" wrapper object, as that is what the client expects. This wrapper is quite simple:

{ "response": { "data" : ACTUAL_DATA } }

Thing is, I'm not a fan of explicitly wrapping each return value for all my request handlers. I also do not like having to unwrap these response wrappers in my unit tests.

Rather, I wonder if it were possible to return the ACTUAL_DATA as it were, and to intercept and wrap this data elsewhere.

If this is in fact possible, would it then be possible to read the annotations attached to the intercepted request handler? This way I can use custom annotations to decide how to wrap the data.

For example something like this would be amazing (note that @FetchResponse and @ResponseWrapper are made up proposed annotations):

@RequestMapping(...)
@FetchResponse
@ResponseBody
public List<User> getUsers() {
    ...
}

@ResponseWrapper(FetchResponse.class)
public Object wrap(Object value) {
    ResponseWrapper rw = new ResponseWrapper();
    rw.setData(value);
    return rw;
}

Anyone familiar with this territory? Or alternatively, and reasons why this might be bad practice?

Body:
For anybody looking on more info on this topic: I was facing the same issue as well, and thanks to the tip of kennyg, i managed to come up with the following solution:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class JSendAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof JSendResponse) {
            return body;
        }

        return new JSendResponse<>().success(body);
    }
}

This solution wraps all the objects returned in your controllers inside a (for this example) JSendResponse class, which saves you the hassle of returning JSendResponses in all of your controller methods.


问:
Calculating the length of a segment in a logarithmic scale
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});```
</div>
</div>
</p>

<p>This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present. </p>

<p>I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)</p>

<p>How should I modify lineLen to use a logarithmic scale?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});</code>```

答:
As long as your events are > 0 you can avoid shifting by scaling the events so the minimum value is above 1. The scalar can be calculated based on a minimum line length in addition to the maximum line length you already have.

// generates an array of line lengths between minLineLength and maxLineLength
// assumes events contains only values > 0 and 0 < minLineLength < maxLineLength
function generateLineLengths(events, minLineLength, maxLineLength) {
  var min = Math.min.apply(null, events);
  var max = Math.max.apply(null, events);

  //calculate scalar that sets line length for the minimum value in events to minLineLength
  var mmr = minLineLength / maxLineLength;
  var scalar = Math.pow(Math.pow(max, mmr) / min, 1 / (1 - mmr));

  function lineLength(x) {
    return maxLineLength * (Math.log(x * scalar) / Math.log(max * scalar));
  }

  return events.map(lineLength)
}

var events = [0.1, 1, 5, 20, 50];

console.log('Between 1 and 20')
generateLineLengths(events, 1, 20).forEach(function(x) {
  console.log(x)
})
// 1
// 8.039722549519123
// 12.960277450480875
// 17.19861274759562
// 20

console.log('Between 5 and 25')
generateLineLengths(events, 5, 25).forEach(function(x) {
  console.log(x)
})
// 5
// 12.410234262651711
// 17.58976573734829
// 22.05117131325855
// 25```

Body:
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});

This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present.

I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)

How should I modify lineLen to use a logarithmic scale?

var maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});


问:
Can i use product flavor to make diffrent apps for single feature from one multi feature app?
Currently, I have an app that contains three features, which is published on the store.

I would like to create a separate app for each feature, but I don't want to copy and paste, since I will then have to maintain multiple codebases.

I have read about Product Flavors, which can be used to create different applications from the same codebase. How do I go about creating four separate apps, while maintaining only one codebase?

Specifically: where do I place the source of the main app that contains all the features?

Can anyone suggest how I can organise my code?

答:
You may want to define compiler switch in product flavor and code base in MAIN and access using BuildConfig.feature1
like </p>

```<code>productFlavors {

            flavor1{
                 buildConfigField "Boolean", "feature1", true;
                 buildConfigField "Boolean", "feature2", false;

                }
          flavor2{
                 buildConfigField "Boolean", "feature1", false;
                 buildConfigField "Boolean", "feature2", true;

                }
           main{
                 buildConfigField "Boolean", "feature1", true;
                 buildConfigField "Boolean", "feature2", true;

                }
}
</code>```

Body:
You may want to define compiler switch in product flavor and code base in MAIN and access using BuildConfig.feature1
like

productFlavors {

            flavor1{
                 buildConfigField "Boolean", "feature1", true;
                 buildConfigField "Boolean", "feature2", false;

                }
          flavor2{
                 buildConfigField "Boolean", "feature1", false;
                 buildConfigField "Boolean", "feature2", true;

                }
           main{
                 buildConfigField "Boolean", "feature1", true;
                 buildConfigField "Boolean", "feature2", true;

                }
}


问:
Partial Classes, LINQ, Interfaces and VB.NET
Okay, I have ran in to a problem with VB.NET. So all those defenders of VB.NET please can you help me out? Here is my issue: I am using LINQ to Entities, it also works with LINQ to SQL, I build my edmx file I then create a Partial Publc Class of the same name as one of the entities All fine up to now, so here comes the problem.

I need the Partial class to implement an Interface Implements Interfaces.IAsset But VB.NET want to place "Implements Interfaces.IAsset.ID" at the end of the property, which of course is in the generated code section of the Partial class, which I can not do as the edmx file is auto generated and will change in the future.

Here is the line of code that needs sorting:

Public Property ID1() As Integer Implements Interfaces.IAsset.ID

In C# it is fine and works wonders. So why can't VB.NET implement an interface that is in the code generated class?

答:
A little bit of indirection in the partial class should do the trick...

```<code>Public Property AssetId() As Int32 Implements IAsset.AssetId
    Get
        Return Id1
    End Get
    Set(ByVal value As Int32)
        Id1 = value
    End Set
End Property
</code>```

The property that implements the interface calls the actual property generated by the dbml.  The class will essentially have two id properties, which is not very elegant but when accessed through the interface you won't know the difference.

Body:
A little bit of indirection in the partial class should do the trick...

Public Property AssetId() As Int32 Implements IAsset.AssetId
    Get
        Return Id1
    End Get
    Set(ByVal value As Int32)
        Id1 = value
    End Set
End Property

The property that implements the interface calls the actual property generated by the dbml.  The class will essentially have two id properties, which is not very elegant but when accessed through the interface you won't know the difference.

OwnerDisplayName: TGnat


问:
Pretty Paths in Rails
I have a category model and I'm routing it using the default scaffolding of resources :categories. I'm wondering if there's a way to change the paths from /category/:id to /category/:name. I added:

```<code>match "/categories/:name" => "categories#show"
</code>```

above the resources line in routes.rb and changed the show action in the controller to do:

```<code>@category = Category.find_by_name(params[:name])
</code>```

it works, but the 'magic paths' such as link_to some_category still use the :id format.

Is there a way to do this? If this is a bad idea (due to some possible way in which rails works internally), is there another way to accomplish this? So that /categories/music, for example, and /categories/3 both work?

答:
Rails has a nifty model instance method called to_param, and it's what the paths use. It defaults to id, but you can override it and produce something like:

```<code>class Category < ActiveRecord::Base
  def to_param
    name
  end
end

cat = Category.find_by_name('music')
category_path(cat)  # => "/categories/music"
</code>```

For more info, check the Rails documentation for to_param.

EDIT:

When it comes to category names which aren't ideal for URLs, you have multiple options. One is, as you say, to gsub whitespaces with hyphens and vice versa when finding the record. However, a safer option would be to create another column on the categories table called name_param (or similar). Then, you can use it instead of the name for, well, all path and URL related business. Use the parameterize inflector to create a URL-safe string. Here's how I'd do it:

```<code>class Category < ActiveRecord::Base
  after_save :create_name_param

  def to_param
    name_param
  end

  private
    def create_name_param
      self.name_param = name.parameterize
    end
end

# Hypothetical
cat = Category.create(:name => 'My. Kewl. Category!!!')
category_path(cat)  # => "/categories/my-kewl-category"

# Controller
@category = Category.find_by_name_param(param[:id]) # <Category id: 123, name: 'My. Kewl. Category!!!'>
</code>```

Title: Pretty Paths in Rails

Body:
I have a category model and I'm routing it using the default scaffolding of resources :categories. I'm wondering if there's a way to change the paths from /category/:id to /category/:name. I added:

match "/categories/:name" => "categories#show"

above the resources line in routes.rb and changed the show action in the controller to do:

@category = Category.find_by_name(params[:name])

it works, but the 'magic paths' such as link_to some_category still use the :id format.

Is there a way to do this? If this is a bad idea (due to some possible way in which rails works internally), is there another way to accomplish this? So that /categories/music, for example, and /categories/3 both work?

Body:
Rails has a nifty model instance method called to_param, and it's what the paths use. It defaults to id, but you can override it and produce something like:

class Category < ActiveRecord::Base
  def to_param
    name
  end
end

cat = Category.find_by_name('music')
category_path(cat)  # => "/categories/music"

For more info, check the Rails documentation for to_param.

EDIT:

When it comes to category names which aren't ideal for URLs, you have multiple options. One is, as you say, to gsub whitespaces with hyphens and vice versa when finding the record. However, a safer option would be to create another column on the categories table called name_param (or similar). Then, you can use it instead of the name for, well, all path and URL related business. Use the parameterize inflector to create a URL-safe string. Here's how I'd do it:

class Category < ActiveRecord::Base
  after_save :create_name_param

  def to_param
    name_param
  end

  private
    def create_name_param
      self.name_param = name.parameterize
    end
end

# Hypothetical
cat = Category.create(:name => 'My. Kewl. Category!!!')
category_path(cat)  # => "/categories/my-kewl-category"

# Controller
@category = Category.find_by_name_param(param[:id]) # <Category id: 123, name: 'My. Kewl. Category!!!'>


问:
Removing axes lines on chart.js
I have been working with some Chart.js and I have been trying to figure out how to remove the axis lines on a chart.

You can see the grid lines I am trying to remove in this image.

I have managed to remove the grid lines that appear within the chart where the data is represented, but I am having an issue removing these two lines.

You can see the chart.js I have created for the chart below.

```<code>var ctx = document.getElementById("volCause").getContext('2d');
var volCause_Doughnut = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
            labels: <?php echo $cause_label_json?>,
        datasets: [{
            backgroundColor: benefactoGraph_colours,
            data: <?php echo $cause_value_json?>

        }]
    },

    options: {
        maintainAspectRatio: false,
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'Volunteer Hours',
                },
                gridLines: {
                    display: false,
                },
            }],

            yAxes: [{
                gridLines: {
                    display: false,

                }
            }]

        }

    }
});
</code>```

Any suggestions would be much appreciated.

答:
You need to set the drawBorder property of grid-lines to false in order to remove those axis lines, like so :

```<code>...
scales: {
   xAxes: [{
      scaleLabel: {
         display: true,
         labelString: 'Volunteer Hours',
      },
      gridLines: {
         display: false,
         drawBorder: false //<- set this
      },
   }],
   yAxes: [{
      gridLines: {
         display: false,
         drawBorder: false //<- set this
      }
   }]
}
...
</code>```

Title: Removing axes lines on chart.js

Body:
I have been working with some Chart.js and I have been trying to figure out how to remove the axis lines on a chart.

You can see the grid lines I am trying to remove in this image.

I have managed to remove the grid lines that appear within the chart where the data is represented, but I am having an issue removing these two lines.

You can see the chart.js I have created for the chart below.

var ctx = document.getElementById("volCause").getContext('2d');
var volCause_Doughnut = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
            labels: <?php echo $cause_label_json?>,
        datasets: [{
            backgroundColor: benefactoGraph_colours,
            data: <?php echo $cause_value_json?>

        }]
    },

    options: {
        maintainAspectRatio: false,
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'Volunteer Hours',
                },
                gridLines: {
                    display: false,
                },
            }],

            yAxes: [{
                gridLines: {
                    display: false,

                }
            }]

        }

    }
});

Any suggestions would be much appreciated.

Body:
You need to set the drawBorder property of grid-lines to false in order to remove those axis lines, like so :

...
scales: {
   xAxes: [{
      scaleLabel: {
         display: true,
         labelString: 'Volunteer Hours',
      },
      gridLines: {
         display: false,
         drawBorder: false //<- set this
      },
   }],
   yAxes: [{
      gridLines: {
         display: false,
         drawBorder: false //<- set this
      }
   }]
}
...


问:
Showing 5 images in a row (Responsive)
I'm trying to display 5 images in a row using Bootstrap. My current code is below:

```<code><div class="container">
  <div class="row text-center">
    <div class="col-sm-2" *ngFor="let smiley of agtContentService.smileys">
      <figure>
        <img src="{{smiley.image}}" width="150" height="150">
        <figcaption>{{smiley.name}}</figcaption>
      </figure>
    </div>
  </div>
</div>
</code>```

The problem currently is that when the images are displayed they are not centered on the screen. Also, they don't stretch/compress depending on screen size. For iOS it is not responsive at all. Can anyone help? What I'm trying to achieve are the below:

Display 5 images with their captions in a row where they take the whole screen size without overlapping and with some space between them.

If the screen size is much smaller (like a mobile phone) they should become smaller up to a specified minimum size and after that, they start to wrap (for e.g. for really small devices, show the images in a column).

Need to work on Android, iOS, Chrome, Safari and Firefox.

Please help. Thanks.

答:
Use <img class="img-responsive">

```<code><div class="container">
  <div class="row text-center">
    <div class="col-sm-2" *ngFor="let smiley of agtContentService.smileys">
      <figure>
        <img class="img-responsive" src="{{smiley.image}}" width="150" height="150">
        <figcaption>{{smiley.name}}</figcaption>
      </figure>
    </div>
  </div>
</div>
</code>```

Title: Showing 5 images in a row (Responsive)

Body:
I'm trying to display 5 images in a row using Bootstrap. My current code is below:

{{smiley.name}}

The problem currently is that when the images are displayed they are not centered on the screen. Also, they don't stretch/compress depending on screen size. For iOS it is not responsive at all. Can anyone help? What I'm trying to achieve are the below:

Display 5 images with their captions in a row where they take the whole screen size without overlapping and with some space between them.

If the screen size is much smaller (like a mobile phone) they should become smaller up to a specified minimum size and after that, they start to wrap (for e.g. for really small devices, show the images in a column).

Need to work on Android, iOS, Chrome, Safari and Firefox.

Please help. Thanks.

Body:
Use <img class="img-responsive">

<div class="container">
  <div class="row text-center">
    <div class="col-sm-2" *ngFor="let smiley of agtContentService.smileys">
      <figure>
        <img class="img-responsive" src="{{smiley.image}}" width="150" height="150">
        <figcaption>{{smiley.name}}</figcaption>
      </figure>
    </div>
  </div>
</div>


问:
angularjs ng-click function is not working in directive
I am trying to bind a click function with an element template , defined in directive. Somehow it is not working for unknown reasons and not throwing any error either.

My html

```<code><body>
    <div ng-app="mainApp">
        <div ng-controller="MyController">
             <div id="Container" class="Container">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>
</code>```

My JS

```<code>var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
    }
})

mainApp.directive('member', function ($compile) {
    //var NewImg = "<img ng-click=ShowChildren() src=../Images/Plus15.png></img>";
    //var NewChild = "<li>"+NewImg+"<span>{{member.TagName}}</span></li>";
    //var NewChild = "<li><img id=dynamic src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";
    var NewChild = "<li><img ng-click=ShowChildren(event) src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";
    //var NewChild = "<li>{{member.TagName}}</li>";

    return {
        restrict: "E",
        replace: false,
        scope: {
            member: '='
        },
        template: NewChild,
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {

                element.append("<collection collection='member.children'></collection>");
                $compile(element.contents())(scope.$new())

                //$compile(collectionSt)(scope, function(cloned, scope)   {
                    //element.append(cloned);
                  //});
            }
        }
    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children
});

function ShowChildren (event) {
    console.log("in function ShowChildren");
    var src = ($(this).attr('src') === '../Images/Plus15.png')
         ? '../Images/Minus15.png'
         : '../Images/Plus15.png';
     $(this).attr('src', src);
    event.stopImmediatePropagation();
}
</code>```

I noticed that , function ShowChildren executes when in put this in directive  but then it again gives problem in "$(this).attr('src') ". And i want it to be in separate files because i will be moving all codes to different javascript file.

Please help me to resolve this.

答:
Your ShowChildren() function is out of the scope of the controller. Put that function into the controller.

controller

```<code>mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children;
    $scope.ShowChildren= function(event) {
         console.log("in function ShowChildren");
         var src = ($(this).attr('src') === '../Images/Plus15.png')
          ? '../Images/Minus15.png'
          :  '../Images/Plus15.png';
          $(this).attr('src', src);
          event.stopImmediatePropagation();
    }
});
</code>```

Directive

```<code>var NewChild = "<li><img ng-click=ShowChildren($event) src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";
</code>```

Body:
I am trying to bind a click function with an element template , defined in directive. Somehow it is not working for unknown reasons and not throwing any error either.

My html

             <collection collection='testdata'></collection>

My JS

var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: "
<member ng-repeat='member in collection' member='member'></member>
"
    }
})

mainApp.directive('member', function ($compile) {
    //var NewImg = "";
    //var NewChild = "
"+NewImg+"{{member.TagName}}
";
    //var NewChild = "
{{member.TagName}}
";
    var NewChild = "
{{member.TagName}}
";
    //var NewChild = "
{{member.TagName}}
";

    return {
        restrict: "E",
        replace: false,
        scope: {
            member: '='
        },
        template: NewChild,
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {

                element.append("<collection collection='member.children'></collection>");
                $compile(element.contents())(scope.$new())

                //$compile(collectionSt)(scope, function(cloned, scope)   {
                    //element.append(cloned);
                  //});
            }
        }
    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children
});

function ShowChildren (event) {
    console.log("in function ShowChildren");
    var src = ($(this).attr('src') === '../Images/Plus15.png')
         ? '../Images/Minus15.png'
         : '../Images/Plus15.png';
     $(this).attr('src', src);
    event.stopImmediatePropagation();
}

I noticed that , function ShowChildren executes when in put this in directive  but then it again gives problem in "$(this).attr('src') ". And i want it to be in separate files because i will be moving all codes to different javascript file.

Please help me to resolve this.

Body:
Your ShowChildren() function is out of the scope of the controller. Put that function into the controller.

controller

mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children;
    $scope.ShowChildren= function(event) {
         console.log("in function ShowChildren");
         var src = ($(this).attr('src') === '../Images/Plus15.png')
          ? '../Images/Minus15.png'
          :  '../Images/Plus15.png';
          $(this).attr('src', src);
          event.stopImmediatePropagation();
    }
});

Directive

var NewChild = "<li><img ng-click=ShowChildren($event) src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";


问:
Scala expression to replace a file extension in a string
Here is a version I wrote using split:

```<code>fileName.split('.').init ++ Seq("js") mkString "."
</code>```

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

答:
What's wrong with lastIndexOf?

```<code>fileName.take(1 + fileName.lastIndexOf(".")) + "js"
</code>```

Of course if you want to keep the fileName when it doesn't contain any dot, you need to do a little bit more

```<code>(if (fileName.contains('.')) fileName.take(fileName.lastIndexOf("."))
else fileName) + ".js"
</code>```

Body:
Here is a version I wrote using split:

fileName.split('.').init ++ Seq("js") mkString "."

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

Body:
What's wrong with lastIndexOf?

fileName.take(1 + fileName.lastIndexOf(".")) + "js"

Of course if you want to keep the fileName when it doesn't contain any dot, you need to do a little bit more

(if (fileName.contains('.')) fileName.take(fileName.lastIndexOf("."))
else fileName) + ".js"


问:
How to stop scrolling as half item can be visible in HorizontalScrollView
Can you plz share any suggestion or library to achieve below,

e.g. If you see in Google Play Store, when you scroll HorizontalScrollView, your scrolling will stop as half of the next item user can able to see. App forcefully stops scroll like this so the user gets to know, there are more items available.

I do not have any code to share. I just want your hints/libs.

Thank you!

答:
You can achieve this by using Snaphelper in RecycleView its available in support libraries
You can attached SnapHelper like this

```<code>SnapHelper startSnapHelper = new StartSnapHelper();
startSnapHelper.attachToRecyclerView(yourRecyclerView);
</code>```

Body:
You can achieve this by using Snaphelper in RecycleView its available in support libraries
You can attached SnapHelper like this

SnapHelper startSnapHelper = new StartSnapHelper();
startSnapHelper.attachToRecyclerView(yourRecyclerView);


问:
SMTPServerDisconnected: Connection unexpectedly closed: timed out
After running the sentry on-premise docker container (version 8.20) and passing in the following eviromental variables:

```<code>-e SENTRY_EMAIL_HOST="smtp.sendgrid.net"
-e SENTRY_EMAIL_PORT=465
-e SENTRY_EMAIL_USE_TLS="True"
-e SENTRY_EMAIL_USER="apikey"
-e SENTRY_EMAIL_PASSWORD= '****'
</code>```

I am receiving the following:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/sentry/tasks/base.py", line 54, in _wrapped
    result = func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/sentry/tasks/email.py", line 76, in send_email
    send_messages([message])
  File "/usr/local/lib/python2.7/site-packages/sentry/utils/email.py", line 415, in send_messages
    sent = connection.send_messages(messages)
  File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 87, in send_messages
    new_conn_created = self.open()
  File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 48, in open
    local_hostname=DNS_NAME.get_fqdn())
  File "/usr/local/lib/python2.7/smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/local/lib/python2.7/smtplib.py", line 317, in connect
    (code, msg) = self.getreply()
  File "/usr/local/lib/python2.7/smtplib.py", line 365, in getreply
    + str(e))
SMTPServerDisconnected: Connection unexpectedly closed: timed out
</code>```

Any one have an idea what might be the cause?

答:
According to Sendgrid Documentation

You can also connect via SSL on port 465.

It seems that currently django.core.mail.backends.smtp.EmailBackend does not support sending emails over ssl and only TSL.

I changed the port to 587 and emails are going through as expected.

Body:
After running the sentry on-premise docker container (version 8.20) and passing in the following eviromental variables:

-e SENTRY_EMAIL_HOST="smtp.sendgrid.net"
-e SENTRY_EMAIL_PORT=465
-e SENTRY_EMAIL_USE_TLS="True"
-e SENTRY_EMAIL_USER="apikey"
-e SENTRY_EMAIL_PASSWORD= '****'

I am receiving the following:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/sentry/tasks/base.py", line 54, in _wrapped
    result = func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/sentry/tasks/email.py", line 76, in send_email
    send_messages([message])
  File "/usr/local/lib/python2.7/site-packages/sentry/utils/email.py", line 415, in send_messages
    sent = connection.send_messages(messages)
  File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 87, in send_messages
    new_conn_created = self.open()
  File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 48, in open
    local_hostname=DNS_NAME.get_fqdn())
  File "/usr/local/lib/python2.7/smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/local/lib/python2.7/smtplib.py", line 317, in connect
    (code, msg) = self.getreply()
  File "/usr/local/lib/python2.7/smtplib.py", line 365, in getreply
    + str(e))
SMTPServerDisconnected: Connection unexpectedly closed: timed out

Any one have an idea what might be the cause?


问:
setting font for a project
currently practicing making an application using android studio.
I have this customized font and saved into res/font directory for the later use.
Inside the activity, i am trying to call getfont(R.font.my_customized_font) with the typeface object. ex) Typeface font = getResources().getfont(R.font.mycustomizedfont)

However, when i try to run the project with the actual device which has the API level 24, it won't activate since the getfont() method requires the min sdk level with 26.

I know that you can set the font of text view in the xml file by doing android:fontfamily but i am using the textswitcher instead of textview.

Emulator works fine by setting up min sdk with 26 but I would like to figure this out by using the actual device.

I found the solution by reading through the developer's website
I just added Typeface font = ResourcesCompat.getfont(context, R.font.mycustomizedfont)

答:
I found the solution by reading through the developer's website I just added Typeface font = ResourcesCompat.getfont(context, R.font.mycustomizedfont)

to apply the font programmatically

Title: setting font for a project


问:
Getting the value of the Javascript receiver in a Seaside JQuery callback
My question is similar to this - how do get what would be javascript this (so that I can get its value assuming its a form text input) ? I am trying to send the value of a text input to the callback you see:

```<code>html textInput id: #thingy;
 onClick: (html jQuery ajax
  callback:[:x | x inspect]
  value:(html jQuery event currentTarget ????));
   with: 'I am the value the poster wants to see inspected in the above callback block!'.
</code>```

答:
To get the value in the ajax callback you would use</p>

```<code>html textInput id: #thingy;
        onClick: (html jQuery ajax
        callback:[:x | x inspect] value: html jQuery new value);
        with: 'I am the value the poster wants to see inspected in the above callback block!'.
</code>```

Body:
My question is similar to this - how do get what would be javascript this (so that I can get its value assuming its a form text input) ? I am trying to send the value of a text input to the callback you see:

html textInput id: #thingy;
 onClick: (html jQuery ajax
  callback:[:x | x inspect]
  value:(html jQuery event currentTarget ????));
   with: 'I am the value the poster wants to see inspected in the above callback block!'.

Body:
To get the value in the ajax callback you would use

html textInput id: #thingy;
        onClick: (html jQuery ajax
        callback:[:x | x inspect] value: html jQuery new value);
        with: 'I am the value the poster wants to see inspected in the above callback block!'.


问:
Error 3004, mapping error with EF
Ok since my of my issues have been resolved,I was flying through the code, until now: I've now run into one I cant even find anything on Google for it. Here's the text of the error:

Error 3004: Problem in mapping

fragments starting at line 937:No
    mapping specified for properties
    StoreItem.ItemPrice in Set StoreItems.
    An Entity with Key (PK) will not
    round-trip when:   Entity is type
    [psychoco_GodsCreationTaxidermyModel.StoreItem]     F:\Projects\GodsCreationTaxidermySVN\GodsCreationTaxidermy.Data\GCTEntities.edmx    938 945 GodsCreationTaxidermy.Data

Of you need any code samples let me know

答:
Just another cause of this that we came across: say we have two developers, A and B.

Dev A adds columns (say "newcol") to a table (say "mytable") in the
database project then updates their model. All builds well, database
has mytable.newcol and the model reflects this.

Dev B pulls/syncs
but forgets to publish the changes to their local database. The
model has mytable.newcol but their local database doesn't.

Dev B then changes the model in some way and updates it from the database,
VS sees that mytable.newcol doesn't exist so it becomes unlinked.

Dev B realises their error and publishes the database changes.

Dev B
then updates the model from the database again. Now VS sees the
mytable.newcol column in the database and creates a mytable.newcol1
(note the suffix) that is linked to the database column, since it
already had an unlinked newcol in the model.

For Dev B, VS then complains that mytable.newcol isn't mapped and
fails.

Solution - to fix, remove mytable.newcol from the model, rename mytable.newcol1 to newcol... or revert to where you were and remember to publish the database before updating the model!

Hope this helps someone.

Title: Error 3004, mapping error with EF


问:
How to unit test with ILogger in ASP.NET Core
This is my controller:

```<code>public class BlogController : Controller
{
    private IDAO<Blog> _blogDAO;
    private readonly ILogger<BlogController> _logger;

    public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
    {
        this._blogDAO = blogDAO;
        this._logger = logger;
    }
    public IActionResult Index()
    {
        var blogs = this._blogDAO.GetMany();
        this._logger.LogInformation("Index page say hello", new object[0]);
        return View(blogs);
    }
}
</code>```

As you can see I have 2 dependencies, a IDAO and a ILogger

And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock DAO easy, but with the ILogger I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?

```<code>public class BlogControllerTest
{
    [Fact]
    public void Index_ReturnAViewResult_WithAListOfBlog()
    {
        var mockRepo = new Mock<IDAO<Blog>>();
        mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
        var controller = new BlogController(null,mockRepo.Object);

        var result = controller.Index();

        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
        Assert.Equal(2, model.Count());
    }
}
</code>```

答:
Actually, I've found Microsoft.Extensions.Logging.Abstractions.NullLogger<> which looks like a perfect solution. Install the package Microsoft.Extensions.Logging.Abstractions, then follow the example to configure and use it:

using Microsoft.Extensions.Logging;

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddSingleton<ILoggerFactory, NullLoggerFactory>();

    ...
}
```

```using Microsoft.Extensions.Logging;

public class MyClass : IMyClass
{
    public const string ErrorMessageILoggerFactoryIsNull = "ILoggerFactory is null";

    private readonly ILogger<MyClass> logger;

    public MyClass(ILoggerFactory loggerFactory)
    {
        if (null == loggerFactory)
        {
            throw new ArgumentNullException(ErrorMessageILoggerFactoryIsNull, (Exception)null);
        }

        this.logger = loggerFactory.CreateLogger<MyClass>();
    }
}
```

<p>and unit test</p>

```//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using Microsoft.Extensions.Logging;

[TestMethod]
public void SampleTest()
{
    ILoggerFactory doesntDoMuch = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory();
    IMyClass testItem = new MyClass(doesntDoMuch);
    Assert.IsNotNull(testItem);
}
```

Body:
This is my controller:

public class BlogController : Controller
{
    private IDAO<Blog> _blogDAO;
    private readonly ILogger<BlogController> _logger;

    public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
    {
        this._blogDAO = blogDAO;
        this._logger = logger;
    }
    public IActionResult Index()
    {
        var blogs = this._blogDAO.GetMany();
        this._logger.LogInformation("Index page say hello", new object[0]);
        return View(blogs);
    }
}

As you can see I have 2 dependencies, a IDAO and a ILogger

And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock DAO easy, but with the ILogger I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?

public class BlogControllerTest
{
    [Fact]
    public void Index_ReturnAViewResult_WithAListOfBlog()
    {
        var mockRepo = new Mock<IDAO<Blog>>();
        mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
        var controller = new BlogController(null,mockRepo.Object);

        var result = controller.Index();

        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
        Assert.Equal(2, model.Count());
    }
}

Body:
Actually, I've found Microsoft.Extensions.Logging.Abstractions.NullLogger<> which looks like a perfect solution. Install the package Microsoft.Extensions.Logging.Abstractions, then follow the example to configure and use it:

using Microsoft.Extensions.Logging;

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddSingleton<ILoggerFactory, NullLoggerFactory>();

    ...
}

using Microsoft.Extensions.Logging;

public class MyClass : IMyClass
{
    public const string ErrorMessageILoggerFactoryIsNull = "ILoggerFactory is null";

    private readonly ILogger<MyClass> logger;

    public MyClass(ILoggerFactory loggerFactory)
    {
        if (null == loggerFactory)
        {
            throw new ArgumentNullException(ErrorMessageILoggerFactoryIsNull, (Exception)null);
        }

        this.logger = loggerFactory.CreateLogger<MyClass>();
    }
}

and unit test

//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using Microsoft.Extensions.Logging;

[TestMethod]
public void SampleTest()
{
    ILoggerFactory doesntDoMuch = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory();
    IMyClass testItem = new MyClass(doesntDoMuch);
    Assert.IsNotNull(testItem);
}

ContentLicense: CC BY-SA 4.0


问:
How to store mySQL query result into pandas DataFrame with pymysql?
I'm trying to store a mySQL query result in a pandas DataFrame using pymysql and am running into errors building the dataframe. Found a similar question here and here, but it looks like there are pymysql-specific errors being thrown:

```<code>import pandas as pd
import datetime
import pymysql

# dummy values
connection = pymysql.connect(user='username', password='password', databse='database_name', host='host')

start_date = datetime.datetime(2017,11,15)
end_date = datetime.datetime(2017,11,16)

try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date))

    df = pd.DataFrame(data=cursor.fetchall(), index = None, columns = cursor.keys())
finally:
    connection.close()
</code>```

returns: AttributeError: 'Cursor' object has no attribute 'keys'

If I drop the index and columns arguments:

```<code>try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date))

    df = pd.DataFrame(cursor.fetchall())
finally:
    connection.close()
</code>```

returns ValueError: DataFrame constructor not properly called!

Thanks in advance!

答:
Use Pandas.read_sql() for this:</p>

```<code>query = "SELECT * FROM orders WHERE date_time BETWEEN ? AND ?"
df = pd.read_sql(query, connection,  params=(start_date, end_date))
</code>```

Body:
I'm trying to store a mySQL query result in a pandas DataFrame using pymysql and am running into errors building the dataframe. Found a similar question here and here, but it looks like there are pymysql-specific errors being thrown:

import pandas as pd
import datetime
import pymysql

# dummy values
connection = pymysql.connect(user='username', password='password', databse='database_name', host='host')

start_date = datetime.datetime(2017,11,15)
end_date = datetime.datetime(2017,11,16)

try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date))

    df = pd.DataFrame(data=cursor.fetchall(), index = None, columns = cursor.keys())
finally:
    connection.close()

returns: AttributeError: 'Cursor' object has no attribute 'keys'

If I drop the index and columns arguments:

try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date))

    df = pd.DataFrame(cursor.fetchall())
finally:
    connection.close()

returns ValueError: DataFrame constructor not properly called!

Thanks in advance!

Body:
Use Pandas.read_sql() for this:

query = "SELECT * FROM orders WHERE date_time BETWEEN ? AND ?"
df = pd.read_sql(query, connection,  params=(start_date, end_date))


问:
How could I keep menu state when page refresh?
I have quite a simple vertical menu which is going to have many levels (online shop)
It works as you can see in the snippet:

$(".boton-BB").click(function () {
  $(this).parent().find('> ul').toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style-type: none;
  padding:0;
  margin:0;
}
.boton-BB {
    display:inline-block;
    position:absolute;
    z-index:1;
    width:25px;
    height:20px;
    background-color:red;
    top:18px;
    right:30px;
    cursor:pointer;
    }
.menu-lateral-BB {
    background-color:#939597;
    font-size:15px;
    line-height:50px;
    font-weight:400;
    min-height:600px;/*PROVISIONAL*/
    }
.menu-lateral-BB a {
    height:100%;
    width:100%;
    padding-left:20px;
    color:#fff;
    white-space:nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right:30px;
    }
.menu-lateral-BB ul {
    width:100%;
    }
.menu-lateral-BB li {
    position:relative;
    width:100%;
    border-top:1px solid #d1d3d4;
    box-shadow: 0 -1px 0 0 #666;
    }
.menu-lateral-BB > ul > li:first-child {border-top:0px solid #d1d3d4; box-shadow: none;}
.menu-lateral-BB > ul > li:last-child {border-bottom:1px solid #666;box-shadow: 0 1px 0 0 #d1d3d4, 0 -1px 0 0 #666;}
.menu-lateral-BB > ul > li ul {display:none;}
.menu-lateral-BB > ul > li ul li a {padding-left:30px;}
.menu-lateral-BB > ul > li ul li ul li a {padding-left:40px;}
.menu-lateral-BB > ul > li ul li ul li ul li a {padding-left:50px;}
.menu-lateral-BB > ul > li ul li ul li ul li ul li a {padding-left:60px;}</code>```

Categoria 3

Subcategoria 1

Subcategoria 2

Categoria 1

Subcategoria 1

Subcategoria 2

sub-Subcategoria 1

sub-Subcategoria 2

Subcategoria 3

```

The jQuery to make it work is quite simple as you just need to click on the red square to open next level.

But I would like to keep the state of the menu with as many "open" levels as the user had when page refreshes (click on the link).

I have tried to use some similar correct answers around with no success.

Is there a simple way to achieve this?

答:
I'd recommend using cookies.

$(".boton-BB").click(function() {
  var button = $(this),
    expires,
    days = 2, //Number of days for how long should the cookie stay
    data = new Date(),
    name = button.data('cat');

  if (button.hasClass("open")) {
    button.parent().find('> ul').hide();

    //delete cookie
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  } else {
    button.parent().find('> ul').show();

    //set cookie
    data.setTime(data.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + data.toGMTString();
    document.cookie = name + "=" + val + expires + "; path=/";
  }
});
```

<pre class="lang-html prettyprint-override"><code><div style="width:400px;position:relative;">
  <div class="menu-lateral-BB">
    <ul>
      <li>
        Categoria 3
        <div class="boton-BB <?= isset($_COOKIE['cat3']) ? " open " : "closed "; ?>" data-cat="cat3"></div>
        <ul <?=i sset($_COOKIE[ 'cat3']) ? "style='display: block;'" : "style='display: none;'"; ?>>
          <li>Subcategoria 1</li>
          <li>Subcategoria 2</li>
        </ul>
      </li>
      <li>
        Categoria 1
        <div class="boton-BB <?= isset($_COOKIE['cat1']) ? " open " : "closed "; ?>" data-cat="cat1"></div>
        <ul <?=i sset($_COOKIE[ 'cat1']) ? "style='display: block;'" : "style='display: none;'"; ?>>
          <li>Subcategoria 1</li>
          <li>Subcategoria 2
            <div class="boton-BB <?= isset($_COOKIE['subcat2']) ? " open " : "closed "; ?>" data-cat="subcat2"></div>
            <ul <?=i sset($_COOKIE[ 'subcat2']) ? "style='display: block;'" : "style='display: none;'"; ?>>
              <li>sub-Subcategoria 1</li>
              <li>sub-Subcategoria 2</li>
            </ul>
          </li>
          <li>Subcategoria 3</li>
        </ul>
      </li>
    </ul>
  </div>
</div>
</code>```

Regards, KJ.

Body:
I have quite a simple vertical menu which is going to have many levels (online shop)
It works as you can see in the snippet:

$(".boton-BB").click(function () {
  $(this).parent().find('> ul').toggle();
});

ul {
  list-style-type: none;
  padding:0;
  margin:0;
}
.boton-BB {
    display:inline-block;
    position:absolute;
    z-index:1;
    width:25px;
    height:20px;
    background-color:red;
    top:18px;
    right:30px;
    cursor:pointer;
    }
.menu-lateral-BB {
    background-color:#939597;
    font-size:15px;
    line-height:50px;
    font-weight:400;
    min-height:600px;/*PROVISIONAL*/
    }
.menu-lateral-BB a {
    height:100%;
    width:100%;
    padding-left:20px;
    color:#fff;
    white-space:nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right:30px;
    }
.menu-lateral-BB ul {
    width:100%;
    }
.menu-lateral-BB li {
    position:relative;
    width:100%;
    border-top:1px solid #d1d3d4;
    box-shadow: 0 -1px 0 0 #666;
    }
.menu-lateral-BB > ul > li:first-child {border-top:0px solid #d1d3d4; box-shadow: none;}
.menu-lateral-BB > ul > li:last-child {border-bottom:1px solid #666;box-shadow: 0 1px 0 0 #d1d3d4, 0 -1px 0 0 #666;}
.menu-lateral-BB > ul > li ul {display:none;}
.menu-lateral-BB > ul > li ul li a {padding-left:30px;}
.menu-lateral-BB > ul > li ul li ul li a {padding-left:40px;}
.menu-lateral-BB > ul > li ul li ul li ul li a {padding-left:50px;}
.menu-lateral-BB > ul > li ul li ul li ul li ul li a {padding-left:60px;}

Categoria 3

Subcategoria 1

Subcategoria 2

Categoria 1

Subcategoria 1

Subcategoria 2

sub-Subcategoria 1

sub-Subcategoria 2

Subcategoria 3

The jQuery to make it work is quite simple as you just need to click on the red square to open next level.

But I would like to keep the state of the menu with as many "open" levels as the user had when page refreshes (click on the link).

I have tried to use some similar correct answers around with no success.

Is there a simple way to achieve this?

Body:
I'd recommend using cookies.

$(".boton-BB").click(function() {
  var button = $(this),
    expires,
    days = 2, //Number of days for how long should the cookie stay
    data = new Date(),
    name = button.data('cat');

  if (button.hasClass("open")) {
    button.parent().find('> ul').hide();

    //delete cookie
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  } else {
    button.parent().find('> ul').show();

    //set cookie
    data.setTime(data.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + data.toGMTString();
    document.cookie = name + "=" + val + expires + "; path=/";
  }
});

<div style="width:400px;position:relative;">
  <div class="menu-lateral-BB">
    <ul>
      <li>
        <a href="#">Categoria 3</a>
        <div class="boton-BB <?= isset($_COOKIE['cat3']) ? " open " : "closed "; ?>" data-cat="cat3"></div>
        <ul <?=i sset($_COOKIE[ 'cat3']) ? "style='display: block;'" : "style='display: none;'"; ?>>
          <li><a href="#">Subcategoria 1</a></li>
          <li><a href="#">Subcategoria 2</a></li>
        </ul>
      </li>
      <li>
        <a href="#">Categoria 1</a>
        <div class="boton-BB <?= isset($_COOKIE['cat1']) ? " open " : "closed "; ?>" data-cat="cat1"></div>
        <ul <?=i sset($_COOKIE[ 'cat1']) ? "style='display: block;'" : "style='display: none;'"; ?>>
          <li><a href="#">Subcategoria 1</a></li>
          <li><a href="#">Subcategoria 2</a>
            <div class="boton-BB <?= isset($_COOKIE['subcat2']) ? " open " : "closed "; ?>" data-cat="subcat2"></div>
            <ul <?=i sset($_COOKIE[ 'subcat2']) ? "style='display: block;'" : "style='display: none;'"; ?>>
              <li><a href="#">sub-Subcategoria 1</a></li>
              <li><a href="#">sub-Subcategoria 2</a></li>
            </ul>
          </li>
          <li><a href="#">Subcategoria 3</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>

Regards, KJ.


答:
you can use below code in your style sheet and tune using the variables.

```<code>.row {
    display: flex;
    flex-wrap: wrap;
    margin: 1em;
    padding: 1em;
  }

.col {
    flex: 1 0 150px;
    margin: 1em;
    min-width: 100px;
    padding: 1em;
  }
</code>```

This is a work around suggested by bootstrap for their flexbox issue with safari and ios.

you can read more about it using the below link

https://getbootstrap.com/docs/4.0/layout/grid/

Below is a working example

https://codepen.io/philipwalton/pen/RPMqjz

Title: Showing 5 images in a row (Responsive)

Body:
you can use below code in your style sheet and tune using the variables.

.row {
    display: flex;
    flex-wrap: wrap;
    margin: 1em;
    padding: 1em;
  }

.col {
    flex: 1 0 150px;
    margin: 1em;
    min-width: 100px;
    padding: 1em;
  }

This is a work around suggested by bootstrap for their flexbox issue with safari and ios.

you can read more about it using the below link

https://getbootstrap.com/docs/4.0/layout/grid/

Below is a working example

https://codepen.io/philipwalton/pen/RPMqjz


问:
sort value not coming where i have used the sort in map
I tried below code
var data =

```<code>[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);
</code>```

ERROR:TypeError: s.name.sort is not a function.

But expecting the output is ["karthik","ramu", "ravi"]

答:
You have used the sort on a string, but it is applicable only on arrays.
You need first get only names, than use sort on the array of names.

Here you can omit the function passed into the sort and use just .sort(), but it will give you some more benefits.

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},      {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},      {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

var names = data.map(s => s.name).sort((a,b) => a.localeCompare(b));
console.log(names);```

Body:
I tried below code
var data =

[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);

ERROR:TypeError: s.name.sort is not a function.

But expecting the output is ["karthik","ramu", "ravi"]


问:
Escape of Escape character not accepted (Java and MySQL)
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

I try to escape the \ (after ss) with

```<code>string statementEsc = statement.replace('\\', '\\\\');
</code>```

this results in:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.

答:
You've got a rogue plus sign in there.

```<code>`CONTACT1_NAME` =  + 'ss\'
</code>```

Hence this SQL is not valid :

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

Suggest you get rid of it in your original String so that you end up with this SQL instead :

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

Another suggestion is to take a look at Prepared Statements. I think they will make your life easier.

Body:
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

I try to escape the \ (after ss) with

string statementEsc = statement.replace('\\', '\\\\');

this results in:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.

Body:
You've got a rogue plus sign in there.

`CONTACT1_NAME` =  + 'ss\'

Hence this SQL is not valid :

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

Suggest you get rid of it in your original String so that you end up with this SQL instead :

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

Another suggestion is to take a look at Prepared Statements. I think they will make your life easier.


问:
Wrong parallel with gfortran compiled by -fopenmp wth specified threads
I wrote a simple code to test the correctness of parallelism.
The subroutine to be called is

```<code>SUBROUTINE two_pt_fn()
IMPLICIT NONE
INTEGER :: i,j
!$OMP PARALLEL DO
DO i=1,10
j=i*2
WRITE(*,*)i,j
END DO
!$OMP END PARALLEL DO
END SUBROUTINE
</code>```

The main program simply calls the above subroutine, and
the source codes are compiled by

```<code>gfortran -fopenmp -o m.x sb_two_pt_fn.f90  main.f90
export OMP_NUM_THREADS=10
</code>```

The result of running

```<code>./m.x
</code>```

gives

```<code>       7          20
       8          16
       9          18
       1          18
       2           4
      10           6
       4           6
       5          10
       6          12
       3          12
</code>```

It's simply multiply the loop index i by 2 but
the result is not correct for every i. Only a few of them are correct.

Why?? I am new to parallel computing with fortran. Besides the answer, nice tutorial document for parallel that includes more complete concept teaching would be very helpful.
Many thanks.

答:
Your openmp section misses the "private" clause for j. i, being the loop variable, is private by default.

As j is not private, several threads will attempt to use use (set its value or use it for printing) at the same time and this leads to inconsistent results.

Solution: add PRIVATE(i,j) at the end of the line !$OMP PARALLEL DO

Body:
I wrote a simple code to test the correctness of parallelism.
The subroutine to be called is

SUBROUTINE two_pt_fn()
IMPLICIT NONE
INTEGER :: i,j
!$OMP PARALLEL DO
DO i=1,10
j=i*2
WRITE(*,*)i,j
END DO
!$OMP END PARALLEL DO
END SUBROUTINE

The main program simply calls the above subroutine, and
the source codes are compiled by

gfortran -fopenmp -o m.x sb_two_pt_fn.f90  main.f90
export OMP_NUM_THREADS=10

The result of running

./m.x

gives

       7          20
       8          16
       9          18
       1          18
       2           4
      10           6
       4           6
       5          10
       6          12
       3          12

It's simply multiply the loop index i by 2 but
the result is not correct for every i. Only a few of them are correct.

Why?? I am new to parallel computing with fortran. Besides the answer, nice tutorial document for parallel that includes more complete concept teaching would be very helpful.
Many thanks.


问:
Set the static IP address of an Azure VM
Trying to create an AD DC in an Azure VM. According to my guide I need to set a static IP address before I install AD DC on the server. I tried doing it but just lead to me losing the connection to the server and having to create a new one.

ipconfig:

Setting static IPv4:

What should I input for the static values in IPv4 above?

答:
You should not alter these values from inside the vm, it might render the vm without networking :) You should alter the NIC ip address configuration.

https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-reserved-private-ip

https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-static-private-ip-arm-pportal


问:
How to stop BackgroundWorker correctly
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

```<code>private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}
</code>```

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?

答: The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again.  How to do this is explained in this SO question.

Title: How to stop BackgroundWorker correctly

Body:
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?