问:
Composer Warning: openssl extension is missing. How to enable in WAMP
Trying to install Composer dependency management tool on Win7/64 + WampServer 2.2 via the Setup Installer and I am getting the following message:

The openssl extension is missing, which will reduce the security and stability of Composer.
  If possible you should enable it or recompile php with --with-openssl

So here is what I did...

From my Wamp icon in Tray,  clicked php > php extensions > php_openssl

This showed that task was completed by placing a check mark beside the extension

I then restarted WampServer

Then from the Wamp icon in tray, I clicked php > php.ini and searched for openssl to verifiy it was NOT commented) out. It was not.

I then went back to Composer-Setup.exe and tried again. Same Warning Message: "openssl extension is missing"

Having never worked with OpenSSL, I'm not sure what is supposed to be set, so I tried to browse to one of my local sites using https. It Failed.

What am I missing?

Please advise.

答:
All those answers are good, but in fact, if you want to understand, the extension directory need to be right if you want all you uncommented extensions to work.  Can write a physical or relative path like

```<code>extension_dir = "C:/myStack/php/ext"
</code>```

or

```<code>extension_dir = "../../php/ext"
</code>```

It's relative to the httpd.exe Apache web server (C:\myStack\apache\bin)
But if you want it to work with Composer or anything you need the physical path because the cli mode doesn't use the web server !

Body:
All those answers are good, but in fact, if you want to understand, the extension directory need to be right if you want all you uncommented extensions to work.  Can write a physical or relative path like

extension_dir = "C:/myStack/php/ext"

or

extension_dir = "../../php/ext"

It's relative to the httpd.exe Apache web server (C:\myStack\apache\bin)
But if you want it to work with Composer or anything you need the physical path because the cli mode doesn't use the web server !


来源: stackexchange

问:
DateTime.UtcNow is 4 hours ahead
I have seen some answers about how to correct this. I have an object of type DateTime. I have assigned this object as shown below.

obj.TimeStamp = DateTime.UtcNow;

I cannot seem to find the right combination or code manipulation to get the correct date and time. It is always exactly 4 hours ahead of what the current time is.

This software will be deployed in various timezones.

Is there any reliable way to ensure the timestamp will be accurate across all time zones. My server time settings are correct.

Thank you.

答:
I know this question is old, but...

```<code>var localDate = DateTime.UtcNow.ToLocalTime()
</code>```

https://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime(v=vs.110).aspx

Read the notes in the MSDN article.  This isnt't foolproof.  But, if you are looking for a way to get the server time, this is a quick and easy way to get about as close as you can w/o getting too crazy.

ContentLicense: CC BY-SA 3.0

Title: DateTime.UtcNow is 4 hours ahead

Body:
I know this question is old, but...

var localDate = DateTime.UtcNow.ToLocalTime()

https://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime(v=vs.110).aspx

Read the notes in the MSDN article.  This isnt't foolproof.  But, if you are looking for a way to get the server time, this is a quick and easy way to get about as close as you can w/o getting too crazy.


问:
Get coordinates of a particular section of the image
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

```<code><img src="image link here" usemap="#mapname">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</code>```

答:
You can use the mouse events clientX, clientY  https://www.w3schools.com/jsref/event_clientx.asp

When you use onmousemove it shows the coordinates

```<code><!DOCTYPE html>
<html>
<body>

<img src="https://i.stack.imgur.com/mDEuy.jpg" usemap="#mapname"
    onmousemove="showCoords(event)">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</img>

<p id="demo"></p>

<script>
    function showCoords(event) {
        var x = event.clientX;
        var y = event.clientY;
        var coords = "X coords: " + x + ", Y coords: " + y;
        document.getElementById("demo").innerHTML = coords;
    }
</script>

</body>
</html>
</code>```

Body:
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>

Body:
You can use the mouse events clientX, clientY  https://www.w3schools.com/jsref/event_clientx.asp

When you use onmousemove it shows the coordinates

<!DOCTYPE html>
<html>
<body>

<img src="https://i.stack.imgur.com/mDEuy.jpg" usemap="#mapname"
    onmousemove="showCoords(event)">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</img>

<p id="demo"></p>

<script>
    function showCoords(event) {
        var x = event.clientX;
        var y = event.clientY;
        var coords = "X coords: " + x + ", Y coords: " + y;
        document.getElementById("demo").innerHTML = coords;
    }
</script>

</body>
</html>


问:
Creating keyboard hotkeys/shortcuts in Word with VBA
For some reason my shortcuts in my normal.dotm files gets deleted once in a while,

so I know i can create shortcuts in word by clicking around in word (https://wordribbon.tips.net/T008058_Assigning_a_Macro_to_a_Shortcut_Key.html)

but I would like to hardcode them instead like I do in excel:

```<code>Sub keyBoardShortCuts()

    Application.OnKey "%^d", "updateDB"
    Application.OnKey "%^p", "openProjectList"
    Application.OnKey "%^m", "addNewLS"
    Application.OnKey "%^l", "createLS"
    Application.OnKey "%^g", "loadGui"
    Application.OnKey "%^b", "Custom_Button_Click"

End Sub
Private Sub Workbook_Open()
    Call keyBoardShortCuts
End Sub
</code>```

However this does not work in word, so what is the syntax to do so in word?

答:
You'll need to use KeyBindings and the constants from Enum WdKey  (press F2 to see the list) :

```<code>With Application.KeyBindings
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyD), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="updateDB"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyP), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="openProjectList"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyM), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="addNewLS"
    '...
End With 'Application.KeyBindings
</code>```

Body:
For some reason my shortcuts in my normal.dotm files gets deleted once in a while,

so I know i can create shortcuts in word by clicking around in word (https://wordribbon.tips.net/T008058_Assigning_a_Macro_to_a_Shortcut_Key.html)

but I would like to hardcode them instead like I do in excel:

Sub keyBoardShortCuts()

    Application.OnKey "%^d", "updateDB"
    Application.OnKey "%^p", "openProjectList"
    Application.OnKey "%^m", "addNewLS"
    Application.OnKey "%^l", "createLS"
    Application.OnKey "%^g", "loadGui"
    Application.OnKey "%^b", "Custom_Button_Click"

End Sub
Private Sub Workbook_Open()
    Call keyBoardShortCuts
End Sub

However this does not work in word, so what is the syntax to do so in word?

Body:
You'll need to use KeyBindings and the constants from Enum WdKey  (press F2 to see the list) :

With Application.KeyBindings
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyD), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="updateDB"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyP), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="openProjectList"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyM), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="addNewLS"
    '...
End With 'Application.KeyBindings


问:
Which one of those two schemas is more scalable?
I'm toying with two schemas and I can't decide which is more scalable. The schema is for a Q&A, and it's built in MySQL. People post questions/answers and like/dislike/favourite questions and answers. A question can have many answers/likes/dislikes, and so can an answer.

To read a question to a user both schemas require the same number of joins, but the joins are handled differently:

Schema 1

```<code>questions(id, title, body, userId)
questionLikes(id, questionId, userId)
questionDislikes(id, questionId, userId)
quetionComments(id, questionId, body, userId)
answers(id, questionId, body, userId)
answerLikes(id, answerId, userId)
answerDislikes(id, answerId, userId)
answerComments(id, answerId, userId, body)
favourites(id, questionId, userId)
</code>```

This is more normalized, easier to develop for, but scalable? Seems to be a lot of repeat information. The join sequence to grab a question is to a user (we want to include his like/dislike activity)

```<code>select question
join answers
join questionLikes
join questionDislikes
join questionComments
join favouites
join answers to answerLikes
join answers to answerDislikes
join answers to answerComments (multiply answer joins by number of answers)
</code>```

Schema 2

```<code>posts(id, postTypeId, userId, title, body)
postTypeId(id, postType)
comments(id, postId, userId)
votes(id, voteTypeId, userId)
voteTypeId(id, voteType)
</code>```

This is less normalized and compact, seems like it would scale better, a pain in the neck with self joins and other development issues (conditional validation). The join sequence to grab a question is

```<code>select question and its answers in the same read using where @id for question, and @questionId for answers; each row, join the following:
join votes on as likes on voteType 1
join votes as dislikes on votetype 2
join comments
join favouites (multiply joins by number of rows)
</code>```

So what will scale better? I know can add some additional fields to store counts so no joins are necessary. But both require the same number of joins and I cant make up my mind.

答:
I would go even further than 2. The question is, what are the entities in your model? Answer: users and posts. A post can be a question, an answer, a vote, a comment or whatever, but it's always a post. Thus

```<code>posts(id, postTypeId, userId, title, body)
postTypeId(id, postType)
</code>```

BTW, both of the selects you mention retrieve everything (or were they just to show the worst possible join?).

I wouldn't see myself fetching his questions and his answers and his comments and... all in one go. Which use case would require everything like that?

ContentLicense: CC BY-SA 2.5

Body:
I'm toying with two schemas and I can't decide which is more scalable. The schema is for a Q&A, and it's built in MySQL. People post questions/answers and like/dislike/favourite questions and answers. A question can have many answers/likes/dislikes, and so can an answer.

To read a question to a user both schemas require the same number of joins, but the joins are handled differently:

Schema 1

questions(id, title, body, userId)
questionLikes(id, questionId, userId)
questionDislikes(id, questionId, userId)
quetionComments(id, questionId, body, userId)
answers(id, questionId, body, userId)
answerLikes(id, answerId, userId)
answerDislikes(id, answerId, userId)
answerComments(id, answerId, userId, body)
favourites(id, questionId, userId)

This is more normalized, easier to develop for, but scalable? Seems to be a lot of repeat information. The join sequence to grab a question is to a user (we want to include his like/dislike activity)

select question
join answers
join questionLikes
join questionDislikes
join questionComments
join favouites
join answers to answerLikes
join answers to answerDislikes
join answers to answerComments (multiply answer joins by number of answers)

Schema 2

posts(id, postTypeId, userId, title, body)
postTypeId(id, postType)
comments(id, postId, userId)
votes(id, voteTypeId, userId)
voteTypeId(id, voteType)

This is less normalized and compact, seems like it would scale better, a pain in the neck with self joins and other development issues (conditional validation). The join sequence to grab a question is

select question and its answers in the same read using where @id for question, and @questionId for answers; each row, join the following:
join votes on as likes on voteType 1
join votes as dislikes on votetype 2
join comments
join favouites (multiply joins by number of rows)

So what will scale better? I know can add some additional fields to store counts so no joins are necessary. But both require the same number of joins and I cant make up my mind.

Body:
I would go even further than 2. The question is, what are the entities in your model? Answer: users and posts. A post can be a question, an answer, a vote, a comment or whatever, but it's always a post. Thus

posts(id, postTypeId, userId, title, body)
postTypeId(id, postType)

BTW, both of the selects you mention retrieve everything (or were they just to show the worst possible join?).

I wouldn't see myself fetching his questions and his answers and his comments and... all in one go. Which use case would require everything like that?


问:
How to get generic argument name via reflection
given generic class

```<code>class Foo<TData> { }
</code>```

and concrete type

```<code>var type = typeof(Foo<string>) //Fpp`[System.String]
var genericType = type.GetGenericTypeDefinition(); //Foo`1[TData]
</code>```

I would like to get "TData". Or the other way: Get the value of the generic argument based on generic argument name:

```<code>GetGenericArgumentType(typeof(Foo<string>), "TData") //should return System.String
</code>```

答:
It's feasible with the following: (this is just for demonstration, it assumes that the type is generic, and the parameter name do exist)</p>

```<code>public string GetGenericArgumentType(Type type, string paramName)
{

    var genericType = type.GetGenericTypeDefinition();

    var genericParam = genericType
        .GetGenericArguments()
        .Select((t, i) => new { Index = i, t.Name })
        .First(arg => arg.Name == paramName);

    return type.GetGenericArguments()[genericParam.Index].Name;
}

class GenericFoo<TData, TSecondData> { }

public void GetGenericArgumentTypeTest()
{
    string name1 = this.GetGenericArgumentType(
                        typeof(GenericFoo<string, int>), "TData"); //String
    string name2 = this.GetGenericArgumentType(
                        typeof(GenericFoo<string, int>), "TSecondData"); //Int32
}
</code>```

Body:
given generic class

class Foo<TData> { }

and concrete type

var type = typeof(Foo<string>) //Fpp`[System.String]
var genericType = type.GetGenericTypeDefinition(); //Foo`1[TData]

I would like to get "TData". Or the other way: Get the value of the generic argument based on generic argument name:

GetGenericArgumentType(typeof(Foo<string>), "TData") //should return System.String

Body:
It's feasible with the following: (this is just for demonstration, it assumes that the type is generic, and the parameter name do exist)

public string GetGenericArgumentType(Type type, string paramName)
{

    var genericType = type.GetGenericTypeDefinition();

    var genericParam = genericType
        .GetGenericArguments()
        .Select((t, i) => new { Index = i, t.Name })
        .First(arg => arg.Name == paramName);

    return type.GetGenericArguments()[genericParam.Index].Name;
}

class GenericFoo<TData, TSecondData> { }

public void GetGenericArgumentTypeTest()
{
    string name1 = this.GetGenericArgumentType(
                        typeof(GenericFoo<string, int>), "TData"); //String
    string name2 = this.GetGenericArgumentType(
                        typeof(GenericFoo<string, int>), "TSecondData"); //Int32
}


问:
Exposing std::vector<struct> with boost.python
I have an existing c++ code library that uses a struct with std::vector, which should be exposed to python.

in the header:

```<code>struct sFOO
{
    unsigned int start = 3 ;
    double foo = 20.0 ;
};
</code>```

in the cpp:

```<code>namespace myName
{
myfoo::myfoo(){
    sFOO singlefoo;
    std::vector<sFOO> foos;
}
sFOO singlefoo;

std::vector<sFOO>* myfoo::get_vector(){
    return &foos;
}
}
</code>```

and for boost::python snippet:

```<code>using namespace boost::python;

class dummy3{};

BOOST_PYTHON_MODULE(vStr)
{
scope myName = class_<dummy3>("myName");

class_<myName::sFOO>("sFOO")
    .add_property("start",&myName::sFOO::start)
    .add_property("foo",&myName::sFOO::foo)
    ;

class_<myName::myfoo>("myfoo", no_init)
    .def(init<>())
    .def("checkfoo",&myName::myfoo::checkfoo)
    .add_property("foos",&myName::myfoo::foos)
    .add_property("singlefoo",&myName::myfoo::singlefoo)
}
</code>```

(FYI, fictitious class dummy3 is used to simulate namespace, and using scope is therefore not an option.)

A compilation and importing processes are OK, and I can access singlefoo, but whenever I try to access vector foos, I encounter the error message below.

```<code>Python class registered for C++ class std::vector<myName::sFOO,
std::allocator<myName::sFOO> >
</code>```

To circumvent this issue,
I've firstly tried vector_indexing_suite, but it didn't help exposing pre-defined vector of struct.

I also assumed that there should be a solution related to exposing pointer to python, so I have tried to get a pointer by following:

```<code>    .def("get_vector",&myName::myfoo::get_vector)
</code>```

which produces compile Error.

Since I am quite a novice to both C++ and Boost, any comments including solution, tips for search, and a suggestion to suitable reference would be greatly appreciated.

Thanks in advance!

答:
Method .def("get_vector",&myName::myfoo::get_vector) is not working because it returns a pointer to a vector, so it's necessary to inform the policy that defines how object ownership should be managed:

```<code>class_<myName::myfoo>("myfoo", no_init)
   // current code
   .def("get_vector", &myfoo::get_vector, return_value_policy<reference_existing_object>())
;
</code>```

In order to use vector_indexing_suite, it is necessary to implement the equal to operator to the class that it holds:

```<code>struct sFOO
{
    unsigned int start = 3 ;
    double foo = 20.0 ;

    bool operator==(const sFOO& rhs)
    {
        return this == &rhs; //< implement your own rules.
    }
};
</code>```

then you can export the vector:

```<code>#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

class_<std::vector<sFOO>>("vector_sFOO_")
   .def(vector_indexing_suite<std::vector<sFOO>>())
;
</code>```

Body:
I have an existing c++ code library that uses a struct with std::vector, which should be exposed to python.

in the header:

struct sFOO
{
    unsigned int start = 3 ;
    double foo = 20.0 ;
};

in the cpp:

namespace myName
{
myfoo::myfoo(){
    sFOO singlefoo;
    std::vector<sFOO> foos;
}
sFOO singlefoo;

std::vector<sFOO>* myfoo::get_vector(){
    return &foos;
}
}

and for boost::python snippet:

using namespace boost::python;

class dummy3{};

BOOST_PYTHON_MODULE(vStr)
{
scope myName = class_<dummy3>("myName");

class_<myName::sFOO>("sFOO")
    .add_property("start",&myName::sFOO::start)
    .add_property("foo",&myName::sFOO::foo)
    ;

class_<myName::myfoo>("myfoo", no_init)
    .def(init<>())
    .def("checkfoo",&myName::myfoo::checkfoo)
    .add_property("foos",&myName::myfoo::foos)
    .add_property("singlefoo",&myName::myfoo::singlefoo)
}

(FYI, fictitious class dummy3 is used to simulate namespace, and using scope is therefore not an option.)

A compilation and importing processes are OK, and I can access singlefoo, but whenever I try to access vector foos, I encounter the error message below.

Python class registered for C++ class std::vector<myName::sFOO,
std::allocator<myName::sFOO> >

To circumvent this issue,
I've firstly tried vector_indexing_suite, but it didn't help exposing pre-defined vector of struct.

I also assumed that there should be a solution related to exposing pointer to python, so I have tried to get a pointer by following:

    .def("get_vector",&myName::myfoo::get_vector)

which produces compile Error.

Since I am quite a novice to both C++ and Boost, any comments including solution, tips for search, and a suggestion to suitable reference would be greatly appreciated.

Thanks in advance!

Body:
Method .def("get_vector",&myName::myfoo::get_vector) is not working because it returns a pointer to a vector, so it's necessary to inform the policy that defines how object ownership should be managed:

class_<myName::myfoo>("myfoo", no_init)
   // current code
   .def("get_vector", &myfoo::get_vector, return_value_policy<reference_existing_object>())
;

In order to use vector_indexing_suite, it is necessary to implement the equal to operator to the class that it holds:

struct sFOO
{
    unsigned int start = 3 ;
    double foo = 20.0 ;

    bool operator==(const sFOO& rhs)
    {
        return this == &rhs; //< implement your own rules.
    }
};

then you can export the vector:

#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

class_<std::vector<sFOO>>("vector_sFOO_")
   .def(vector_indexing_suite<std::vector<sFOO>>())
;


问:
How to get the valid part of a regex match
I want to test if a user string is "ok so far", in that it might not be valid as a whole but it is a subset of a valid one.

I have a regex say ^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]$
such that "1234-1234-5678-5678" is valid

"1234-12" or even "1"  does not match pattern but its a valid subset of a valid format, in other words the input is ok so far.

is there a neat way of doing this without making many many regexes,    its friday.

答:
You could possibly use one final regex for validation of the form you currently have, and a on the fly regex for the user input being valid for each subset.

My idea would be to have ([0-9]{1,4}-)+


问:
Asp.net MVC - paypal ipn
i am trying to integrate paypal sandox with my MVC project. I have enabled AutoReturn and ipn, i have disabled PDT.

After payment is made, in the auto-return page, i get

Request.HttpMethod --> GET
HttpContext.Request.ContentLength --> 0
Request.Form.Keys.Count --> 0

if i enable PDT also, i get the same result

can anyone please solve this

答:
If I understand you correctly, you're saying that your AutoReturn is issuing a GET with no parameters. Isn't this as designed? The AutoReturn is simply a redirect for the user, and doesn't necessarily need to contain any form parameters.

The IPN is what should be issuing you a POST. The IPN and AutoReturn URLs are two different values -- are both set up in your PayPal Manager?

Perhaps you could post some of your PayPal Manager settings/screenshots?

Title: Asp.net MVC - paypal ipn


问:
Kubernetes: single POD with many container, or many Pod with single container
I've rather a teoretical question which I can't answer  with the reousrces found online. The question is: what's the rule to decide how to compose containers in POD? . Let me explain with an example.

I've these microservices:

Authentication

Authorization

Serving content

(plus) OpenResty to forward the calls form one to the other and orhcestarate the flow. (is there a possibility to do so natively in K8?, it seems to have services base on nginx+lua, but not sure how it works)

For the sake of the example I avoid Databases and co, I assume they are external and not managed by kubernetes

Now, what's the correct way here LEFT or RIGHT of the image?

LEFT : this seems easier to make it working, everything works on "localhost" , the downside is that it looses a bit the benefit of the microservices. For example, if the auth become slows and it would need more instances, I've to duplicate the whole pod and not just that service.

RIGHT seems a bit more complex, need services to expose each POD to the other PODs. Yet, here, I could duplicate auth as I need without duplicating the other containers. On the other hand I'll have a lot of pods since each pod is basically a container.

答:
right image, each in own pod.  multi containers in a pod should really only be used when they are highly coupled or needed for support of the main container such as a data loader.

With separate pods, it allows for each service to be updated and deployed independently.  It also allows for more efficient scaling. in the future, you may need 2 or 3 content pods but still only one authorization. if they are all together you scale them all since you don't have a choice with them all together in the same pod.


问:
How to calculate some values using shell script between all files so that the output is all-by-all matrix?
I am having some problems getting a shell script running properly. I am not getting the desired output. I have 3 files:

Sample File1

```<code>>A3IC_00
ATGGACCGCCTCGTCAACCGGATTCGCGCCAACGCGTGGGGTTCGCTCACGGCCATCCCCGAACTGCTCGGCGTCGCCCCCACCGGCGAACCGCAGGCCGAGCTGTGGATGGGAGCCCACCCGGGCGCGCCCTCCCGGATCGACCGGGGCCGCGGGCCGTGCTCGCTGGTCGAGCTGATCGCCGCCGACCCCGAGGGCGAGCTCGGCGCGGACACCGCGGCCCGGTTCGGCCCGCGGCTGCCGTTCCTGCTCAAGGTGCTGGCCGCGGAGGAGCCGCTGTCGCTCCAGGTGCACCCGGACGCGATCCAGGCCCGGCACGGCTACGCGGAGGAGGAGGCGCGCGGCGTCCCGATCGACGCGCCGCACCGCAACTACCGCGACTCCAGCCACAAGCCGGAGATGATCTGCGCGCTCGGCGACTTCGAGGGCCTGGTCGGCTATCGCGAGATCGCCGAGACACTCAAGCTGCTCGACGCCCTCGACGTCCCGGAACTGGCTCCGTTCGCACGCGCGTTGCGCAATCCCGACCAGGAGGCGGCACTGCGCGCGGCGACCACGCACGTGCTCATGCTGCCCGCCCGCCTGCGCACCGGCGTGGTCGACGCGGTGGCCGCGGCCTGTCGGCGGCTGGCCGCGAACG
</code>```

Sample File2

```<code>>AW19M42_00
ATGGACCGGCTCTCCAACACCGTGCGCCCGTACGCCTGGGGCTCCACCACAGCCATCCCCGCCCTGCTGGGTGTCGCCCCCACCGGCGAGCCCCAGGCCGAGATGTGGATGGGCGCCCACCCCGGGGCCCCCTCCCGGATAACCCGCACCGGCCCCGCCACCGCACCCGACGCCACGCCCGGCACCCCGCAGACCCCCACCGAGCAGCCCCTCACCGACGTCATCGCCGCCGATCCGGTGGGCGAGCTGGGCCCGGCCGCCGTCGAGAAGTTCGGCCCCCGGCTCCCCTTCCTCCTCAAGCTGCTCGCCGCCGGAGCACCGCTCTCCCTCCAGGTCCACCCCGACCTCGCCCAGGCACAGCAGGGTTACGCGGACGAGGAGCGCCGGTCCGTCCCGATCGACGCCCCCCACCGCACGTACAAGGACGCCAACCACAAGCCCGAACTGATCTGCGCGCTCACCCCCTTCGACGGCCTGTGCGGCTTCCGCCGGCCCATCGAGGCGGCCGAGACGATGGAGGCGCTGGGCGTCGACTCCCTCAAGCCCTACGCCGACCTGCTGCGCGCCCACCCCGAGGAGGACGCCCTGCGCGAGGTCCTCACGGCGATCCTCACCGCGGACCCGGCGCAGATGGCGGAGACGGTGACCGCCGCGGCCGCGGCCGCGGAACGGCTCGGCGGCGCCTACGCCCCGTACGCGCGCATCGCCCACCACTTCCCGGGCGACGCGGGCGTCATCGCGGCCATGCTGCTGAACTACGTGCGACTCCAGCCCGGCGAGGCGCTGTTTCTCGGCGCCGGGGTCCCGCACGCCTACCTCGACGGCCTCGGCGTCGAGATCA
</code>```

Sample File3

```<code>>B072_00
ATGGACCGCCTCACCAACACCGTCCGCCCCTACGCCTGGGGCTCCACCACCGCCATCCCGCGGCTCGTCGGCGCCGAGCCGACCGGCGAACCCCAGGCCGAGATGTGGATGGGCGCCCACCCCGGCGCCCCCTCCCGCACCGAGCGCGGCCCGCTGAACGAGGTCATCGACGCGGCCCCCGCGCAGGAGCTGGGCGAGCCGGCCGTGACCAAGTTCGGCCCCCGCCTCCCCTTCCTCCTCAAGCTGCTCGCCGCGGGCGCCCCCCTCTCCCTCCAGGTGCATCCGAACCTCCAGCAGGCGAAGGAGGGTTACGAGAAGGAAGAGGCCCAGGGCGTTCCCATCGACGCCCCGCACCGCAACTACAAGGACGCCAACCACAAGCCCGAACTCATCTGCGCGCTCACCGAGTTCGACGGCCTGTGCGGCTTCCGCGCCCCCGAGGAGGCGGCCCGGCTCCTCGAAGGCCTCGGCGTCGACAGCCTCAAGCCGTACGTGGACCTGCTGCGCGCCCACCCCGAGGAGGCCGCGCTGCGCGAGGTCCTCACGGCCGTCCTGTCCGCGGACCTCGCCGAGATGACGGCCACCGTCACCGAGGCGACCGCCGCCGCCCAGCGCATCGGCGGCGACTACGAGCCGTACGCGGGCATCGCCCACCACTACCCCGGCGACCCGGGCGTCATCGCGGCCATGCTCCTCAATCACGTACGCCTGCAGCCGGGCGAGGCGCTCTTCCTCGGCGCCGGCGTCCCGCACGCGTACCTGAACGGCCTCGGCGTCGAGATCATGGCCAACTCCGACAACGTCCTGCGCTGCGGCCTCACGCCGAAGCACGTCG
</code>```

...and I need to do some calculations for all the possible pairs between these 3 files, i.e. the output should be 3x3 matrix. The script reads name of the 3 files from list2.txt.

Here is my code:

```<code>list=`cat list2.txt`
for id in $list
do
echo "processing .........................................$id"

orthoani=`java -jar OAT_cmd.jar -blastplus_dir ~/ncbi-blast-2.5.0+/bin/ \
          -method ani -fasta1 $id.fasta -fasta2 $id.fasta | \
          grep "OrthoANI :"`
echo "$id $id $orthoani" >> tmp00-orthoANI.txt
done
</code>```

Sample Output:

```<code>    A3IC_00 A3IC_00 OrthoANI : 100.0 (%)
    AW19M42_00 AW19M42_00 OrthoANI : 100.0 (%)
    B072_00 B072_00 OrthoANI : 100.0 (%)
</code>```

Desired output:

```<code>    A3IC_00 A3IC_00 OrthoANI : 100.0 (%)
    A3IC_00 AW19M42_00 OrthoANI : 70.0 (%)
    A3IC_00 B072_00 OrthoANI : 65.0 (%)
    AW19M42_00 AW19M42_00 OrthoANI : 100.0 (%)
    AW19M42_00 A3IC_00 OrthoANI : 70.0 (%)
    AW19M42_00 B072_00 OrthoANI : 87.0 (%)
    B072_00 B072_00 OrthoANI : 100.0 (%)
    B072_00 A3IC_00 OrthoANI : 65.0 (%)
    B072_00 AW19M42_00 OrthoANI : 87.0 (%)
</code>```

Any help will be highly appreciated.

Thanks.

答:
Observations:

The desired output includes lines where the first two fields are different, like:

```<code>B072_00 AW19M42_00 OrthoANI : 87.0 (%)
</code>```

At present that output is impossible because the code that outputs the first two fields uses the same variable twice (i.e. "$id $id..."):

```<code>echo "$id $id $orthoani" >> tmp00-orthoANI.txt
</code>```

Since this code always seems to compare $id.fasta to itself:

```<code>java -jar OAT_cmd.jar -blastplus_dir ~/ncbi-blast-2.5.0+/bin/ \
     -method ani -fasta1 $id.fasta -fasta2 $id.fasta
</code>```

The result must be %100.

Needlessly complicated:

```<code>list=`cat list2.txt`
for id in $list
    < .....etc. >
done
</code>```

Simpler:

```<code>while read id
    < .....etc. >
done < list2.txt
</code>```

Body:
I am having some problems getting a shell script running properly. I am not getting the desired output. I have 3 files:

Sample File1

>A3IC_00
ATGGACCGCCTCGTCAACCGGATTCGCGCCAACGCGTGGGGTTCGCTCACGGCCATCCCCGAACTGCTCGGCGTCGCCCCCACCGGCGAACCGCAGGCCGAGCTGTGGATGGGAGCCCACCCGGGCGCGCCCTCCCGGATCGACCGGGGCCGCGGGCCGTGCTCGCTGGTCGAGCTGATCGCCGCCGACCCCGAGGGCGAGCTCGGCGCGGACACCGCGGCCCGGTTCGGCCCGCGGCTGCCGTTCCTGCTCAAGGTGCTGGCCGCGGAGGAGCCGCTGTCGCTCCAGGTGCACCCGGACGCGATCCAGGCCCGGCACGGCTACGCGGAGGAGGAGGCGCGCGGCGTCCCGATCGACGCGCCGCACCGCAACTACCGCGACTCCAGCCACAAGCCGGAGATGATCTGCGCGCTCGGCGACTTCGAGGGCCTGGTCGGCTATCGCGAGATCGCCGAGACACTCAAGCTGCTCGACGCCCTCGACGTCCCGGAACTGGCTCCGTTCGCACGCGCGTTGCGCAATCCCGACCAGGAGGCGGCACTGCGCGCGGCGACCACGCACGTGCTCATGCTGCCCGCCCGCCTGCGCACCGGCGTGGTCGACGCGGTGGCCGCGGCCTGTCGGCGGCTGGCCGCGAACG

Sample File2

>AW19M42_00
ATGGACCGGCTCTCCAACACCGTGCGCCCGTACGCCTGGGGCTCCACCACAGCCATCCCCGCCCTGCTGGGTGTCGCCCCCACCGGCGAGCCCCAGGCCGAGATGTGGATGGGCGCCCACCCCGGGGCCCCCTCCCGGATAACCCGCACCGGCCCCGCCACCGCACCCGACGCCACGCCCGGCACCCCGCAGACCCCCACCGAGCAGCCCCTCACCGACGTCATCGCCGCCGATCCGGTGGGCGAGCTGGGCCCGGCCGCCGTCGAGAAGTTCGGCCCCCGGCTCCCCTTCCTCCTCAAGCTGCTCGCCGCCGGAGCACCGCTCTCCCTCCAGGTCCACCCCGACCTCGCCCAGGCACAGCAGGGTTACGCGGACGAGGAGCGCCGGTCCGTCCCGATCGACGCCCCCCACCGCACGTACAAGGACGCCAACCACAAGCCCGAACTGATCTGCGCGCTCACCCCCTTCGACGGCCTGTGCGGCTTCCGCCGGCCCATCGAGGCGGCCGAGACGATGGAGGCGCTGGGCGTCGACTCCCTCAAGCCCTACGCCGACCTGCTGCGCGCCCACCCCGAGGAGGACGCCCTGCGCGAGGTCCTCACGGCGATCCTCACCGCGGACCCGGCGCAGATGGCGGAGACGGTGACCGCCGCGGCCGCGGCCGCGGAACGGCTCGGCGGCGCCTACGCCCCGTACGCGCGCATCGCCCACCACTTCCCGGGCGACGCGGGCGTCATCGCGGCCATGCTGCTGAACTACGTGCGACTCCAGCCCGGCGAGGCGCTGTTTCTCGGCGCCGGGGTCCCGCACGCCTACCTCGACGGCCTCGGCGTCGAGATCA

Sample File3

>B072_00
ATGGACCGCCTCACCAACACCGTCCGCCCCTACGCCTGGGGCTCCACCACCGCCATCCCGCGGCTCGTCGGCGCCGAGCCGACCGGCGAACCCCAGGCCGAGATGTGGATGGGCGCCCACCCCGGCGCCCCCTCCCGCACCGAGCGCGGCCCGCTGAACGAGGTCATCGACGCGGCCCCCGCGCAGGAGCTGGGCGAGCCGGCCGTGACCAAGTTCGGCCCCCGCCTCCCCTTCCTCCTCAAGCTGCTCGCCGCGGGCGCCCCCCTCTCCCTCCAGGTGCATCCGAACCTCCAGCAGGCGAAGGAGGGTTACGAGAAGGAAGAGGCCCAGGGCGTTCCCATCGACGCCCCGCACCGCAACTACAAGGACGCCAACCACAAGCCCGAACTCATCTGCGCGCTCACCGAGTTCGACGGCCTGTGCGGCTTCCGCGCCCCCGAGGAGGCGGCCCGGCTCCTCGAAGGCCTCGGCGTCGACAGCCTCAAGCCGTACGTGGACCTGCTGCGCGCCCACCCCGAGGAGGCCGCGCTGCGCGAGGTCCTCACGGCCGTCCTGTCCGCGGACCTCGCCGAGATGACGGCCACCGTCACCGAGGCGACCGCCGCCGCCCAGCGCATCGGCGGCGACTACGAGCCGTACGCGGGCATCGCCCACCACTACCCCGGCGACCCGGGCGTCATCGCGGCCATGCTCCTCAATCACGTACGCCTGCAGCCGGGCGAGGCGCTCTTCCTCGGCGCCGGCGTCCCGCACGCGTACCTGAACGGCCTCGGCGTCGAGATCATGGCCAACTCCGACAACGTCCTGCGCTGCGGCCTCACGCCGAAGCACGTCG

...and I need to do some calculations for all the possible pairs between these 3 files, i.e. the output should be 3x3 matrix. The script reads name of the 3 files from list2.txt.

Here is my code:

list=`cat list2.txt`
for id in $list
do
echo "processing .........................................$id"

orthoani=`java -jar OAT_cmd.jar -blastplus_dir ~/ncbi-blast-2.5.0+/bin/ \
          -method ani -fasta1 $id.fasta -fasta2 $id.fasta | \
          grep "OrthoANI :"`
echo "$id $id $orthoani" >> tmp00-orthoANI.txt
done

Sample Output:

    A3IC_00 A3IC_00 OrthoANI : 100.0 (%)
    AW19M42_00 AW19M42_00 OrthoANI : 100.0 (%)
    B072_00 B072_00 OrthoANI : 100.0 (%)

Desired output:

    A3IC_00 A3IC_00 OrthoANI : 100.0 (%)
    A3IC_00 AW19M42_00 OrthoANI : 70.0 (%)
    A3IC_00 B072_00 OrthoANI : 65.0 (%)
    AW19M42_00 AW19M42_00 OrthoANI : 100.0 (%)
    AW19M42_00 A3IC_00 OrthoANI : 70.0 (%)
    AW19M42_00 B072_00 OrthoANI : 87.0 (%)
    B072_00 B072_00 OrthoANI : 100.0 (%)
    B072_00 A3IC_00 OrthoANI : 65.0 (%)
    B072_00 AW19M42_00 OrthoANI : 87.0 (%)

Any help will be highly appreciated.

Thanks.

Body:
Observations:

The desired output includes lines where the first two fields are different, like:

B072_00 AW19M42_00 OrthoANI : 87.0 (%)

At present that output is impossible because the code that outputs the first two fields uses the same variable twice (i.e. "$id $id..."):

echo "$id $id $orthoani" >> tmp00-orthoANI.txt

Since this code always seems to compare $id.fasta to itself:

java -jar OAT_cmd.jar -blastplus_dir ~/ncbi-blast-2.5.0+/bin/ \
     -method ani -fasta1 $id.fasta -fasta2 $id.fasta

The result must be %100.

Needlessly complicated:

list=`cat list2.txt`
for id in $list
    < .....etc. >
done

Simpler:

while read id
    < .....etc. >
done < list2.txt


问:
SQL server 2008 , conditional select query
Please help me to form this query.

I have a table like this:

```<code>Row Product   Role
-------------------
1   ABC-1     Self
2   ABC-2     Self
3   ABC-2     Joint
4   ABC-3     Self
5   ABC-3     Joint
6   ABC-4     Self
</code>```

I want to fetch only those  product rows where Role is Self only. In other words from the given table the SQL query should output only rows 1 & 6. Output should look like this

```<code>Row Product   Role
-------------------
1   ABC-1     Self
6   ABC-4     Self
</code>```

Thank you

答:
You can use NOT EXISTS:

```<code>SELECT *
FROM dbo.YourTable t
WHERE NOT EXISTS(SELECT 1 FROM dbo.YourTable
                 WHERE Product = t.Product
                 AND Role <> 'Self');
</code>```

Body:
Please help me to form this query.

I have a table like this:

Row Product   Role
-------------------
1   ABC-1     Self
2   ABC-2     Self
3   ABC-2     Joint
4   ABC-3     Self
5   ABC-3     Joint
6   ABC-4     Self

I want to fetch only those  product rows where Role is Self only. In other words from the given table the SQL query should output only rows 1 & 6. Output should look like this

Row Product   Role
-------------------
1   ABC-1     Self
6   ABC-4     Self

Thank you

Body:
You can use NOT EXISTS:

SELECT *
FROM dbo.YourTable t
WHERE NOT EXISTS(SELECT 1 FROM dbo.YourTable
                 WHERE Product = t.Product
                 AND Role <> 'Self');


问:
Elixir & Phoenix - ArgumentError at GET /users/new
I am trying to implement user authentication with the Phoenix web framework on Elixir but stumped by this error.

If I run changeset = Blog.User.changeset(%Blog.User{}) inside iex I get the following error:

```<code>** (ArgumentError) unknown field "email" for changeset on
%Blog.User{__meta__: #Ecto.Schema.Metadata<:built, "users">, email:
nil, id: nil, inserted_at: nil, is_admin: false, name: nil, password:
nil, password_hash: nil, posts: #Ecto.Association.NotLoaded<association
:posts is not loaded>, updated_at: nil}
  (ecto) lib/ecto/changeset.ex:1318: Ecto.Changeset.ensure_field_exists!/2
  (ecto) lib/ecto/changeset.ex:1305: anonymous fn/5 in Ecto.Changeset.validate_required/3
  (elixir) lib/enum.ex:1755: Enum."-reduce/3-lists^foldl/2-0-"/3
  (ecto) lib/ecto/changeset.ex:1304: Ecto.Changeset.validate_required/3
</code>```

Here is my model web/models/user.ex:

```<code>defmodule Blog.User do
  use Blog.Web, :model

  schema "users" do
    field :email, :string
    field :name, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :is_admin, :boolean, default: false

    has_many :posts, Blog.Post

    timestamps()
  end

  @required_fields ~w(email)
  @optional_fields ~w(name is_admin)
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
  end
end
</code>```

答:
Ecto.Changeset.cast/3 converts keys to atoms, so for cast you can use strings, but Ecto.Changeset.validate_required/3 has to deal with keys as atoms, so your @required_fields should be list of atoms.

By the way- there should be sigil ~a for that.

Body:
I am trying to implement user authentication with the Phoenix web framework on Elixir but stumped by this error.

If I run changeset = Blog.User.changeset(%Blog.User{}) inside iex I get the following error:

** (ArgumentError) unknown field "email" for changeset on
%Blog.User{__meta__: #Ecto.Schema.Metadata<:built, "users">, email:
nil, id: nil, inserted_at: nil, is_admin: false, name: nil, password:
nil, password_hash: nil, posts: #Ecto.Association.NotLoaded<association
:posts is not loaded>, updated_at: nil}
  (ecto) lib/ecto/changeset.ex:1318: Ecto.Changeset.ensure_field_exists!/2
  (ecto) lib/ecto/changeset.ex:1305: anonymous fn/5 in Ecto.Changeset.validate_required/3
  (elixir) lib/enum.ex:1755: Enum."-reduce/3-lists^foldl/2-0-"/3
  (ecto) lib/ecto/changeset.ex:1304: Ecto.Changeset.validate_required/3

Here is my model web/models/user.ex:

defmodule Blog.User do
  use Blog.Web, :model

  schema "users" do
    field :email, :string
    field :name, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :is_admin, :boolean, default: false

    has_many :posts, Blog.Post

    timestamps()
  end

  @required_fields ~w(email)
  @optional_fields ~w(name is_admin)
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
  end
end


问:
SQLite don't order by date
I need a selection of all the elements of the table, sorted according to the column where there are dates

this is the table create code:

```<code>String query = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ( "+
            " id INTEGER PRIMARY KEY,"+
            " "+ COLUMN_LIST +" TEXT,"+
            " "+ COLUMN_PRICE + " TEXT,"+
            " "+ COLUMN_EXPIRY + " NUMERIC,"+
            " "+ COLUMN_DATE +" NUMERIC,"+
            " f_k INTEGER,"+
            " FOREIGN KEY(f_k) REFERENCES user(id)"+
            " ON DELETE CASCADE"+
            ")";
</code>```

This is the code to insert elements in the column that I need to be ordered:

```<code>try{
    VAL.put( COLUMN_EXPIRY, String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
}catch( ParseException e ){
    e.printStackTrace();
}
</code>```

the items.get( 2 ).toString() is stringDate variable:

```<code>int day = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();

stringDate = Integer.toString( day ) +"-"+ Integer.toString( month ) +"-"+ Integer.toString( year );
</code>```

the code of select element:

```<code>final String QUERY = SELECT_ALL + t;
final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
final Cursor RESULT = DB.rawQuery( QUERY + ORDER, null );
</code>```

the result does not satisfy me. the dates are not in order.
Also some elements of the column are null and I would put down the list using a different order taken by another column.

thank you

答:
To avoid a complex query you could try storing the elements of the date in separate fields:

```<code>    " "+ COLUMN_EXPIRY_day + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_month + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_year + " NUMERIC,"+
</code>```

And your query's Order By clause:

```<code>ORDER BY COLUMN_EXPIRY_year, COLUMN_EXPIRY_month, COLUMN_EXPIRY_day
</code>```

Title: SQLite don't order by date

Body:
I need a selection of all the elements of the table, sorted according to the column where there are dates

this is the table create code:

String query = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ( "+
            " id INTEGER PRIMARY KEY,"+
            " "+ COLUMN_LIST +" TEXT,"+
            " "+ COLUMN_PRICE + " TEXT,"+
            " "+ COLUMN_EXPIRY + " NUMERIC,"+
            " "+ COLUMN_DATE +" NUMERIC,"+
            " f_k INTEGER,"+
            " FOREIGN KEY(f_k) REFERENCES user(id)"+
            " ON DELETE CASCADE"+
            ")";

This is the code to insert elements in the column that I need to be ordered:

try{
    VAL.put( COLUMN_EXPIRY, String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
}catch( ParseException e ){
    e.printStackTrace();
}

the items.get( 2 ).toString() is stringDate variable:

int day = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();

stringDate = Integer.toString( day ) +"-"+ Integer.toString( month ) +"-"+ Integer.toString( year );

the code of select element:

final String QUERY = SELECT_ALL + t;
final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
final Cursor RESULT = DB.rawQuery( QUERY + ORDER, null );

the result does not satisfy me. the dates are not in order.
Also some elements of the column are null and I would put down the list using a different order taken by another column.

thank you

Body:
To avoid a complex query you could try storing the elements of the date in separate fields:

    " "+ COLUMN_EXPIRY_day + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_month + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_year + " NUMERIC,"+

And your query's Order By clause:

ORDER BY COLUMN_EXPIRY_year, COLUMN_EXPIRY_month, COLUMN_EXPIRY_day


问:
Getting values of keys from a rdd of maps in scala
I have an RDD which has maps as its elements. I cannot use RDD.get, of course. So, as of now, I do the following to get values for keys from this map:

```<code>val x = RDD.collect().flatten.toMap
</code>```

and then

```<code>x.get(key)
</code>```

to get the value for the key. Now, have a really big rdd which outputs the error java.lang.OutOfMemoryError: GC overhead limit exceeded as I am applying .collect() on the rdd. How can I do it without applying .collect() on the rdd?

答:
Since you can't fit everything onto your driver, you first need to filter the RDD for the map you need to look into, and then do the get...</p>

```<code>val rdd = sc.parallelize(List(Map("a"->1,"b"->2),Map("c"->3,"d"->4)))

val key = "d"

val filteredRDD = rdd.filter(_.keySet contains key)

if (!filteredRDD.isEmpty) filteredRDD.first.get(key) else None
</code>```

Body:
I have an RDD which has maps as its elements. I cannot use RDD.get, of course. So, as of now, I do the following to get values for keys from this map:

val x = RDD.collect().flatten.toMap

and then

x.get(key)

to get the value for the key. Now, have a really big rdd which outputs the error java.lang.OutOfMemoryError: GC overhead limit exceeded as I am applying .collect() on the rdd. How can I do it without applying .collect() on the rdd?

Body:
Since you can't fit everything onto your driver, you first need to filter the RDD for the map you need to look into, and then do the get...

val rdd = sc.parallelize(List(Map("a"->1,"b"->2),Map("c"->3,"d"->4)))

val key = "d"

val filteredRDD = rdd.filter(_.keySet contains key)

if (!filteredRDD.isEmpty) filteredRDD.first.get(key) else None


问:
WooCommerce changing "SSSSS" text-based ratings to default Star-ratings
For those who know WooCommerce, this may seem like a simple fix. Well, I am totally stumped...

My theme overwrites WooCommerce's star-rating system with an ugly "progress bar" style ratings system. First, I worked on getting rid of this (successfully) and switched it to text based ratings such as "4 out of 5".

Next, I used a ton of CSS taken from another WooCommerce website to change the "4 out of 5" on the individual product pages, however I am absolutely stumped on the overall shop page.

Here's my shop page: thebrains timulator.net/shop
Here's what the original "progress bars" looked like: http://demo.woothemes.com/function/shop/ (see "Castillo Hat")

Here's the code I was able to implement to change the individual product pages from the textual ratings to stars:

```<code>.woocommerce div.product .woocommerce-product-rating {
    margin-bottom: 1.618em;
}
.woocommerce .woocommerce-product-rating:after, .woocommerce .woocommerce-product-rating:before {
    content: " ";
    display: table;
}
.woocommerce .woocommerce-product-rating .star-rating {
    margin: .5em 4px 0 0;
    float: left;
}
.woocommerce .star-rating {
    float: right;
    overflow: hidden;
    position: relative;
    height: 1em;
    line-height: 1;
    font-size: 1em;
    width: 5.4em;
    font-family: star;
}
.woocommerce .star-rating:before {
    content: "\73\73\73\73\73";
    color: #d3ced2;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    font-family = "star";
}
.woocommerce .star-rating span {
    overflow: hidden;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    padding-top: 1.5em;
    font-family = "star";
}
.woocommerce .star-rating span:before {
    content: "\53\53\53\53\53";
    top: 0;
    position: absolute;
    left: 0;
    font-family: star;
    visibility: visible;
}
</code>```

Once the above code was implemented, my shop page changed from the "5 out of 5" text to S's, which is GREAT! (so I thought) because that's actually what WooCommerce uses for to show star-ratings! Uppercase and lower case S's relate to the filled and unfilled star ratings.

However, no matter how I try to tailor the above code to my Shop page, I cannot crack the code. Still stuck with S's...

Any suggestions?

EDIT I was able to get the S's on the shop page to convert to stars by removing the "//Disable Woocommerce styles" code located at the top of this file: wp-content/themes/function/includes/integrations/woocommerce/woocommerce.php
However, removing it screwed up the look of my product pages...

```<code><?php
if ( ! defined( 'ABSPATH' ) ) exit;

global $woo_options;

add_theme_support( 'woocommerce' );

// Disable WooCommerce styles
if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) {
    // WooCommerce 2.1 or above is active
    add_filter( 'woocommerce_enqueue_styles', '__return_false' );
} else {
    // WooCommerce less than 2.1 is active
    define( 'WOOCOMMERCE_USE_CSS', false );
}

// Load WooCommerce stylsheet
if ( ! is_admin() ) { add_action( 'wp_enqueue_scripts', 'woo_load_woocommerce_css', 20 ); }

if ( ! function_exists( 'woo_load_woocommerce_css' ) ) {
    function woo_load_woocommerce_css () {
        wp_register_style( 'woocommerce', esc_url( get_template_directory_uri() . '/includes/integrations/woocommerce/css/woocommerce.css' ) );
        wp_enqueue_style( 'woocommerce' );
    } // End woo_load_woocommerce_css()
}
</code>```

Any further suggestions?

答:
I'd add a custom post class that you can use to distinguish your CSS and make it more specific than your theme's CSS.

```<code>add_filter( 'post_class', 'so_43142741_post_class', 10, 2 );
function so_43142741_post_class( $classes, $post_id ){
    if( 'product' == get_post_type( $post_id ) ){
        $classes[] = 'use-star-ratings';
    }
    return $classes;
}
</code>```

Then your CSS would look like:

```<code>.woocommerce div.product.use-star-rating .woocommerce-product-rating {
    margin-bottom: 1.618em;
}
</code>```

EDIT It appears that your theme's custom woocommerce.css doesn't have any font-face declarations.

I'd recommend copying all the WooCommerce star fonts into a fonts folder in your theme and then adding the font-face declaration to your child theme's CSS.

```<code>@font-face {
    font-family: 'star';
    src: url('fonts/star.eot');
    src: url('fonts/star.eot?#iefix') format('embedded-opentype'),
        url('fonts/star.woff') format('woff'),
        url('fonts/star.ttf') format('truetype'),
        url('fonts/star.svg#star') format('svg');
    font-weight: normal;
    font-style: normal;
}
</code>```

Alternatively, you could sort out the relative paths from your theme to the WooCommerce plugin folder but this is probably easier.

Body:
For those who know WooCommerce, this may seem like a simple fix. Well, I am totally stumped...

My theme overwrites WooCommerce's star-rating system with an ugly "progress bar" style ratings system. First, I worked on getting rid of this (successfully) and switched it to text based ratings such as "4 out of 5".

Next, I used a ton of CSS taken from another WooCommerce website to change the "4 out of 5" on the individual product pages, however I am absolutely stumped on the overall shop page.

Here's my shop page: thebrains timulator.net/shop
Here's what the original "progress bars" looked like: http://demo.woothemes.com/function/shop/ (see "Castillo Hat")

Here's the code I was able to implement to change the individual product pages from the textual ratings to stars:

.woocommerce div.product .woocommerce-product-rating {
    margin-bottom: 1.618em;
}
.woocommerce .woocommerce-product-rating:after, .woocommerce .woocommerce-product-rating:before {
    content: " ";
    display: table;
}
.woocommerce .woocommerce-product-rating .star-rating {
    margin: .5em 4px 0 0;
    float: left;
}
.woocommerce .star-rating {
    float: right;
    overflow: hidden;
    position: relative;
    height: 1em;
    line-height: 1;
    font-size: 1em;
    width: 5.4em;
    font-family: star;
}
.woocommerce .star-rating:before {
    content: "\73\73\73\73\73";
    color: #d3ced2;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    font-family = "star";
}
.woocommerce .star-rating span {
    overflow: hidden;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    padding-top: 1.5em;
    font-family = "star";
}
.woocommerce .star-rating span:before {
    content: "\53\53\53\53\53";
    top: 0;
    position: absolute;
    left: 0;
    font-family: star;
    visibility: visible;
}

Once the above code was implemented, my shop page changed from the "5 out of 5" text to S's, which is GREAT! (so I thought) because that's actually what WooCommerce uses for to show star-ratings! Uppercase and lower case S's relate to the filled and unfilled star ratings.

However, no matter how I try to tailor the above code to my Shop page, I cannot crack the code. Still stuck with S's...

Any suggestions?

EDIT I was able to get the S's on the shop page to convert to stars by removing the "//Disable Woocommerce styles" code located at the top of this file: wp-content/themes/function/includes/integrations/woocommerce/woocommerce.php
However, removing it screwed up the look of my product pages...

<?php
if ( ! defined( 'ABSPATH' ) ) exit;

global $woo_options;

add_theme_support( 'woocommerce' );

// Disable WooCommerce styles
if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) {
    // WooCommerce 2.1 or above is active
    add_filter( 'woocommerce_enqueue_styles', '__return_false' );
} else {
    // WooCommerce less than 2.1 is active
    define( 'WOOCOMMERCE_USE_CSS', false );
}

// Load WooCommerce stylsheet
if ( ! is_admin() ) { add_action( 'wp_enqueue_scripts', 'woo_load_woocommerce_css', 20 ); }

if ( ! function_exists( 'woo_load_woocommerce_css' ) ) {
    function woo_load_woocommerce_css () {
        wp_register_style( 'woocommerce', esc_url( get_template_directory_uri() . '/includes/integrations/woocommerce/css/woocommerce.css' ) );
        wp_enqueue_style( 'woocommerce' );
    } // End woo_load_woocommerce_css()
}

Any further suggestions?

Body:
I'd add a custom post class that you can use to distinguish your CSS and make it more specific than your theme's CSS.

add_filter( 'post_class', 'so_43142741_post_class', 10, 2 );
function so_43142741_post_class( $classes, $post_id ){
    if( 'product' == get_post_type( $post_id ) ){
        $classes[] = 'use-star-ratings';
    }
    return $classes;
}

Then your CSS would look like:

.woocommerce div.product.use-star-rating .woocommerce-product-rating {
    margin-bottom: 1.618em;
}

EDIT It appears that your theme's custom woocommerce.css doesn't have any font-face declarations.

I'd recommend copying all the WooCommerce star fonts into a fonts folder in your theme and then adding the font-face declaration to your child theme's CSS.

@font-face {
    font-family: 'star';
    src: url('fonts/star.eot');
    src: url('fonts/star.eot?#iefix') format('embedded-opentype'),
        url('fonts/star.woff') format('woff'),
        url('fonts/star.ttf') format('truetype'),
        url('fonts/star.svg#star') format('svg');
    font-weight: normal;
    font-style: normal;
}

Alternatively, you could sort out the relative paths from your theme to the WooCommerce plugin folder but this is probably easier.


问:
How can I make a today alert display all of the information I need?
I'm using Forismatic API to get a random inspirational quote whidh I'd like to show as a widget. I have it set up, and I have a button that generates a new quote, however I cannot get it to always display a quote/author. It seems that it's due to the length of the quote, and it running off of the constraints I've set. The error I get is:

Error parsing json: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid
  escape sequence around character 54."
  UserInfo={NSDebugDescription=Invalid escape sequence around character
  54.}

Also, how can I get the text to display starting at the top left corner?

The quotes are displaying like this, starting more in the middle of the entire label area, not the top left:

答:
The error you are getting has nothing to do with your views/constraints - it means that there was an unexpected character in your JSON payload, and the system couldn't parse it. Without seeing the payload it is inpossible to say what this character might be.

As to placing the text in the top - there is no way to specify vertical alignement in UILabel. You can achieve this by setting the labels bottom constraint to be greater than or equal to 0 ( or some margin value ). This will stick the label to the top, and let it grow to accomodate more text.


问:
How do I build JSON dynamically in javascript?
```<code>var myJSON = {
              "list1" : [ "1", "2" ],
              "list2" : [ "a", "b" ],
              "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
              "not_a_list" : "11"
             };
</code>```

How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:

```<code>var myJSON = {};
</code>```

答:
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

```<code>// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';
</code>```

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

ContentLicense: CC BY-SA 4.0

Body:
var myJSON = {
              "list1" : [ "1", "2" ],
              "list2" : [ "a", "b" ],
              "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
              "not_a_list" : "11"
             };

How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:

var myJSON = {};

Body:
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.


问:
Sum data from array by parameters php
This is the array that I get from a query:

```<code>Array (
       [0] => Array (
                     [0] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ADELE
                                    [GOLD] => 160
                                    [NORMAL] => 0
                                    [TOTAL] => 160
                                  )
                     [1] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ALESSO
                                    [GOLD] => 1320
                                    [NORMAL] => 550
                                    [TOTAL] => 1870
                                  )
                     [2] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ANASTACIA
                                    [GOLD] => 440
                                    [NORMAL] => 150
                                    [TOTAL] => 590
                                   )
                     [3] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 420
                                    [NORMAL] => 120
                                    [TOTAL] => 540
                                   )
                     [4] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 440
                                    [NORMAL] => 100
                                    [TOTAL] => 540
                                   )
                     [5] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 640
                                    [NORMAL] => 0
                                    [TOTAL] => 640
                                   )
                     [6] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 440
                                    [NORMAL] => 440
                                    [TOTAL] => 880
                                   )
                    )

     )
)
</code>```

The keys GOLD and NORMAL can be differents, depend of the query, but I would like to sum the total from GOLD, NORMAL and TOTAL by PRODUCT, something like this, you can omit VARIETY:

```<code>Array(
      [0] => Array(
                   [PRODUCT] => ROSE
                   [GOLD]    => 1920
                   [NORMAL]  => 700
                   [TOTAL]   => 2620
                  )
      [1] => Array(
                   [PRODUCT] => ROSE1
                   [GOLD]    => 860
                   [NORMAL]  => 220
                   [TOTAL]   => 1080
                  )
      [2] => Array(
                   [PRODUCT] => ROSE2
                   [GOLD]    => 1080
                   [NORMAL]  => 440
                   [TOTAL]   => 1520
                  )
)
</code>```

I have tried somenthing like this:
$harvest is the array with the data

```<code>//This get the array_keys from the data
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
   array_push($arrayThead, array_keys($harvest[$i][0]));
}

$arrayfoot= array();

foreach ($harvest as $key => $value) {
  foreach ($value as $harv) {
     foreach ($arrayThead as $key => $values) {
        foreach ($values as $th) {
           if($th != 'PRODUCT' && $th != 'VARIETY'){
               $arrayfoot[$th] += $harv[$th];
           }
        }
     }
  }
}
</code>```

But at this point it totalizes the data with all the PRODUCTS in general:

```<code>Array (
        [GOLD] => 3850
        [NORMAL] => 1360
        [TOTAL] => 5220
      )
</code>```

UPDATED

This is the mysql query:

```<code>SELECT pr_products.product AS PRODUCT,
            pr_varieties.variety AS VARIETY,
            FORMAT(SUM(IF(pr_grades.grade='GOLD',pf_harvest.quantity,0)),0) AS GOLD,
            SUM(IF(pr_grades.grade='NORMAL',pf_harvest.quantity,0)) AS NORMAL,
            SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = CURDATE()
GROUP BY pf_harvest.id_product, pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade
</code>```

How can I add the data to arm an array as in the example I have explained?
Thanks!

答:
```<code>$aProductsArray = array(
    array(
            "PRODUCT" => "ROSE",
            "GOLD"    => 1920,
            "NORMAL" => 700,
            "TOTAL"   => 2620,
        ),
    array(
            "PRODUCT" => "ROSE1",
            "GOLD"   => 860,
            "NORMAL" => 220,
            "TOTAL"   => 1080,
        ),
    array(
            "PRODUCT" => "ROSE2",
            "GOLD"    => 1080,
            "NORMAL"  => 440,
            "TOTAL"   => 1520
        )
);
$sumArray = array();
foreach ($aProductsArray as $k=>$subArray) {
    foreach ($subArray as $id=>$value) {
        if(is_numeric($value)){
            $sumArray[$id]+=$value;
        }
    }
}
print_r($sumArray);
</code>```

Title: Sum data from array by parameters php

Body:
This is the array that I get from a query:

Array (
       [0] => Array (
                     [0] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ADELE
                                    [GOLD] => 160
                                    [NORMAL] => 0
                                    [TOTAL] => 160
                                  )
                     [1] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ALESSO
                                    [GOLD] => 1320
                                    [NORMAL] => 550
                                    [TOTAL] => 1870
                                  )
                     [2] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ANASTACIA
                                    [GOLD] => 440
                                    [NORMAL] => 150
                                    [TOTAL] => 590
                                   )
                     [3] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 420
                                    [NORMAL] => 120
                                    [TOTAL] => 540
                                   )
                     [4] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 440
                                    [NORMAL] => 100
                                    [TOTAL] => 540
                                   )
                     [5] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 640
                                    [NORMAL] => 0
                                    [TOTAL] => 640
                                   )
                     [6] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 440
                                    [NORMAL] => 440
                                    [TOTAL] => 880
                                   )
                    )

     )
)

The keys GOLD and NORMAL can be differents, depend of the query, but I would like to sum the total from GOLD, NORMAL and TOTAL by PRODUCT, something like this, you can omit VARIETY:

Array(
      [0] => Array(
                   [PRODUCT] => ROSE
                   [GOLD]    => 1920
                   [NORMAL]  => 700
                   [TOTAL]   => 2620
                  )
      [1] => Array(
                   [PRODUCT] => ROSE1
                   [GOLD]    => 860
                   [NORMAL]  => 220
                   [TOTAL]   => 1080
                  )
      [2] => Array(
                   [PRODUCT] => ROSE2
                   [GOLD]    => 1080
                   [NORMAL]  => 440
                   [TOTAL]   => 1520
                  )
)

I have tried somenthing like this:
$harvest is the array with the data

//This get the array_keys from the data
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
   array_push($arrayThead, array_keys($harvest[$i][0]));
}

$arrayfoot= array();

foreach ($harvest as $key => $value) {
  foreach ($value as $harv) {
     foreach ($arrayThead as $key => $values) {
        foreach ($values as $th) {
           if($th != 'PRODUCT' && $th != 'VARIETY'){
               $arrayfoot[$th] += $harv[$th];
           }
        }
     }
  }
}

But at this point it totalizes the data with all the PRODUCTS in general:

Array (
        [GOLD] => 3850
        [NORMAL] => 1360
        [TOTAL] => 5220
      )

UPDATED

This is the mysql query:

SELECT pr_products.product AS PRODUCT,
            pr_varieties.variety AS VARIETY,
            FORMAT(SUM(IF(pr_grades.grade='GOLD',pf_harvest.quantity,0)),0) AS GOLD,
            SUM(IF(pr_grades.grade='NORMAL',pf_harvest.quantity,0)) AS NORMAL,
            SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = CURDATE()
GROUP BY pf_harvest.id_product, pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade

How can I add the data to arm an array as in the example I have explained?
Thanks!


答:
You can use a WHERE NOT EXISTS for this:

```<code>Select  *
From    YourTable   T
Where Not Exists
(
    Select  *
    From    YourTable   T1
    Where   T.Product = T1.Product
    And     T1.[Role] <> 'Self'
)
And    T.[Role] = 'Self'
</code>```

Title: SQL server 2008 , conditional select query

Body:
You can use a WHERE NOT EXISTS for this:

Select  *
From    YourTable   T
Where Not Exists
(
    Select  *
    From    YourTable   T1
    Where   T.Product = T1.Product
    And     T1.[Role] <> 'Self'
)
And    T.[Role] = 'Self'


问:
Mongodb data is not returned to nodejs api
I am able to connect to mongodb through my nodejs api but for some reason data is not returned. When i query mongodb from console , here is what i get :

```<code>MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
</code>```

here is the code from nodejs:

```<code>app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

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

and this is getPatients method:

```<code>var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){

    Patient.find(callback);
}
</code>```

But the browser always shows "[]" and no data. When i look at length of array ( console.log(patients.length)) in API , i get 0. Not sure why data is not returned.
Can someone pls point me what may be the issue ?

Update

Based on suggestions, I did following changes. I created 2 collections just to make sure that the collection exists. So i have patient and patients collections.

```<code>MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
</code>```

Here is the code from nodejs file:

```<code>var mongoose = require('mongoose');

var patientSchema = mongoose.Schema({
    FName: {
        type : String
     },
     LName: {
        type : String
     },

     Email: {
        type : String
     },
     phone: {
        type : String
     },

},
{collection : 'patient'});

var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){
console.log('test2');
 Patient.find({}, function(err, patients) {
  if (err) throw err;

  // object of all the users
  console.log(patients.length);
});
}
</code>```

when i run this code, it prints 'test2' and '0' for me but not actual results. Can someone help with this ?

答:
I figured my code was correct but connection string was incorrect.

Incorrect Connection string :

mongoose.connect('mongodb://localhost:27017/');

Correct connection string:

mongoose.connect('mongodb://localhost:27017/patients');

Body:
I am able to connect to mongodb through my nodejs api but for some reason data is not returned. When i query mongodb from console , here is what i get :

MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "abc@yahoo.com", "phone" : "1234567890" }

here is the code from nodejs:

app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});

and this is getPatients method:

var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){

    Patient.find(callback);
}

But the browser always shows "[]" and no data. When i look at length of array ( console.log(patients.length)) in API , i get 0. Not sure why data is not returned.
Can someone pls point me what may be the issue ?

Update

Based on suggestions, I did following changes. I created 2 collections just to make sure that the collection exists. So i have patient and patients collections.

MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }

Here is the code from nodejs file:

var mongoose = require('mongoose');

var patientSchema = mongoose.Schema({
    FName: {
        type : String
     },
     LName: {
        type : String
     },

     Email: {
        type : String
     },
     phone: {
        type : String
     },

},
{collection : 'patient'});

var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){
console.log('test2');
 Patient.find({}, function(err, patients) {
  if (err) throw err;

  // object of all the users
  console.log(patients.length);
});
}

when i run this code, it prints 'test2' and '0' for me but not actual results. Can someone help with this ?


问:
IE8 losing session cookies in popup windows
We have an ASP.NET application that uses Forms Auth. When users log in, a session ID cookie and a Forms Auth ticket (stored as a cookie) are generated. These are session cookies, not permanent cookies. It is intentional and desirable that when the browser closes, the user is effectively logged out.

Once a user logs in, a new window is popped up using window.open('location here');. The page that is opened is effectively the workspace the user works in throughout the rest of their session. From this page, other pop-ups are also used.

Lately, we've had a number of customers (all using latest versions of IE8) complaining that the when they log in, the initial pop-up takes them back to the log in screen rather than their homepage. Alternately, users can sometimes log in, get to the homepage (which again, is in a new pop up window), and it all seems fine, until any additional pop-ups are created, where it starts redirecting them to the log in screen again.

In attempting to troubleshoot the issue, I've used good old Fiddler. When the problem starts manifesting, I've noticed that the browser is not sending up the ASP.NET session ID session cookie OR the Forms Auth ticket session cookie, even though the response to the log in POST clearly pushes down those cookies.

What's more strange is if I CTRL+N to open a new window from the popped-up window that is missing the session cookies, then manually type in the URL to the home page, those cookies magically appear again. However, subsequent window.open(); calls will continue to be broken, not sending the session cookies and taking the user to the log in screen.

It's important to note that sometimes, for seemingly no good reason, those same users can suddenly log in and work normally for a while, then it goes back to broken.

Now, I've ensured that there are no browser add-ons, plug-ins, toolbars, etc. are running. I've added our site as a trusted site and dropped the security settings to Low, I've modified the Cookie Privacy policy to "accept all" and even disabled automatic policy settings, manually forcing it to accept everything and include session cookies. Nothing appears to affect it.

Also note the web application resides on a single server. There is no load balancing, web gardens, server farms, clusters, etc. The server does reside behind an ISA server, but other than that it's pretty straight forward.

I've been searching around for days and haven't found anything actionable. Heck, sometimes I can't even reproduce it reliably. I have found a few references to people having this same problem, but they seem to be referencing an issue that was allegedly fixed in a beta or RC release (example: IE8 loses cookies when opening a new window after a redirect). These are release versions of IE, with up-to-date patches.

I'm aware that I can try to set permanent cookies instead of session cookies. However, this has drastic security implications for our application.

Update

It seems that the problem automagically goes away when the user is added as a Local Administrator on the machine. Only time will tell if this change permanently (and positively) affects this problem.

Time to bust out ProcMon and see if there is a resource access problem.

Update #2

It seems there are multiple angles to what appears to be a singular problem. I reported long ago that making the user a local administrator seemed to help. And it did, for a number of users. Of course, that's not really a solution, but it did let us hobble along.

Then more users started reporting the issue, and the admin fix was not helping. The users seemed to be mostly Win7, but Vista was also affected. They also seemed to mostly be 64-bit installations.

Setting the TabProcGrowth to 0 or 1 (either worked) as suggested by some members below seems to have largely addressed the issue. So, I'm going to move my accepted answer to the first person that suggested that, as it has had significantly more impact.

This has been an incredibly frustrating issue to attempt to solve, since it is difficult to reproduce and often occurs with users that I do not have direct communication with, or by the time I get to them it doesn't appear to be working. All I can say is something is not right with the session merging feature, but I don't have much data to feed to Microsoft to find a permanent fix.

答:
I also found a workable fix for this problem. There seems to be a problem with how IE8 handles opening servlets in another window with a relative path such as /test. It seems to be opening a new session as well as a new window. Our workable fix is that instead of opening a new window with a relative path, we just used a jsp page. So when we navigate to a URL, we do not navigate to /test anymore.We navigate to a specific file. In the jsp file, we forward the request to the relative path. This seems to work, which is kind of awkward, since the only difference is that we are placing a specific file in between.

I hope this helps.


问:
Laravel Many-to-one relationship
I have two tables:

```<code>orders
-id
-status_id

status
-id
-label
</code>```

Relations are:

Any Order has one status

```<code>public function status()
{
    return $this->hasOne('App\Status');
}
</code>```

Any Status can belong to many orders

```<code>public function orders()
{
    return $this->belongsToMany('App\Order');
}
</code>```

I suppose it is correct?

Now,if I use:

```<code>    $o = Status::with('orders')->get();
</code>```

I get all the orders.
If I use:

```<code>    $o = Order::with('status')->get();
</code>```

I get an error!
Column not found: 1054 Unknown column 'status.order_id' in 'where clause' (SQL: select * from status where status.order_id in (1, 2, 3, 4, 5))
But I don't have status.order_id, instead I have order.status_id.

How do I get the label of order's status? Like order->status->label?

答:
You have to use hasMany for a one-to-many relation. Your orders function should be like this:

```<code>public function orders()
{
    return $this->hasMany('App\Order');
}
</code>```

The function for status should be belongsTo.

```<code>public function status()
{
    return $this->belongsTo('App\Status');
}
</code>```

belongsToMany is used for many-to-many relation with a pivot table.

Title: Laravel Many-to-one relationship

Body:
I have two tables:

orders
-id
-status_id

status
-id
-label

Relations are:

Any Order has one status

public function status()
{
    return $this->hasOne('App\Status');
}

Any Status can belong to many orders

public function orders()
{
    return $this->belongsToMany('App\Order');
}

I suppose it is correct?

Now,if I use:

    $o = Status::with('orders')->get();

I get all the orders.
If I use:

    $o = Order::with('status')->get();

I get an error!
Column not found: 1054 Unknown column 'status.order_id' in 'where clause' (SQL: select * from status where status.order_id in (1, 2, 3, 4, 5))
But I don't have status.order_id, instead I have order.status_id.

How do I get the label of order's status? Like order->status->label?

Body:
You have to use hasMany for a one-to-many relation. Your orders function should be like this:

public function orders()
{
    return $this->hasMany('App\Order');
}

The function for status should be belongsTo.

public function status()
{
    return $this->belongsTo('App\Status');
}

belongsToMany is used for many-to-many relation with a pivot table.


问:
Recoding floats in a list
I have a list of floats, which looks like this:

```<code>predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]
</code>```

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)
</code>```

This code seems to work, but the funny thing is that:

```<code>len(predictions_dec)
1222
len(predictions_clean)
1816
</code>```

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

答:
You need to replace the second if with elif:

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    elif pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)
</code>```

Title: Recoding floats in a list

Body:
I have a list of floats, which looks like this:

predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)

This code seems to work, but the funny thing is that:

len(predictions_dec)
1222
len(predictions_clean)
1816

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

Body:
You need to replace the second if with elif:

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    elif pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)


问:
Parse TSQL scripts and return table and column usage
we are currently involved in a data migration project, for which we have to analyze data usage, meaning we need to figure out which tables and columns are used and need to be migrated and which data is obsolete.
We not only have many SSRS reports based on stored procedures, we also have hundreds if not thousands of TSQL scripts used for ad hoc analyzes. Analyzing them one by one by hand is virtually impossible.

I looked for a way to parse these scripts and return the data used by the scripts. I managed to write a macro in EditPad which extracts tables from a script, but I failed to do the same for columns. The main problems here are aliases, CTEs and even distinguishing column names in the script from other commands.

In contrast to a simple regex based macro, SQL Server must have a clear idea which columns are used by the script -> Execution plan.
Is there any way we could use this capability for our purposes? Or even better: is there any third party tool that could do what we need? So far, I could not find anything.

Thx very much for any advice!

答:
Parsing out tables and columns from execution plans may be possible, but it can’t be simple to do. (I’ll be watching this post in case someone spells it out.) Third party tools might to do this, another thing to watch for. From my experience, I’m thinking this may not be feasible, not to the full extent that you need.

A lateral approach: can you arrange to “run everything” against the database, so that you know all possible attempts to access your data have been hit? If so:

Create a copy of the database.

Only include as little data as necessary for the queries to work.

(So, either backup/restore, or use SSMS to “script out" the database)

Configure security such that the login used can access nothing

Run the first query. It will fail. Determine what tables and column it needs access to. Grant access to only those tables and columns.

Run the next query. Repeat.

Odds are you can run batches of queries and add tables/columns en masse

Save time by enabling the known/obvious tables first

Once all queries can be successfully run because all the relevant tables and columns are enabled, you have your minimal set.

The thing is… having written that, I see so many potential caveats, fringe cases and gotchas (that totally depend upon what you have to work with—what about views? Triggers? Synonyms?) that I have to question whether it’s worth the effort. If you’re certain you’ll cut out half the database, go for it, but for a 10% reduction it might not be worth the effort. (For a 10% reduction, try just renaming the most suspect tables and see what happens.)


答:
If it is truly Maps then you can do the following:

```<code>rdd.flatMap(identity).lookup(key)
</code>```

Although this will still output to the driver, but only the values from that key. So, if that can fit in memory then you are good with that. But if you want to work with it as an rdd still then:

```<code>rdd.flatMap(identity)
   .flatMap{case (key, value) => if(key == myKey) Some(value) else None}
</code>```

And should you want key AND value then you can turn the flatMap into a filter and just filter on key == myKey

Title: Getting values of keys from a rdd of maps in scala

Body:
If it is truly Maps then you can do the following:

rdd.flatMap(identity).lookup(key)

Although this will still output to the driver, but only the values from that key. So, if that can fit in memory then you are good with that. But if you want to work with it as an rdd still then:

rdd.flatMap(identity)
   .flatMap{case (key, value) => if(key == myKey) Some(value) else None}

And should you want key AND value then you can turn the flatMap into a filter and just filter on key == myKey


问:
Is there a way to generate xml schema (xsd) in .net core runtime?
I have an issue to publish xml schemas (.xsd) for the some types with .Net Core. It should be runtime and cross-platform. Is there a way to do it?

答: According the .NET Core Roadmap and team member comment here, this is planned to be a part of .Net Core 1.2 release on Q2 2017.


问:
Recursive Components in AngularJS 1.x
Finally trying to learn AngularJS and I can't quite figure out how to make components work recursively. I have a simple example that's not rendering as expected.

HTML

```<code><body ng-app="myApp" ng-controller="myCtrl as vm">
  <nested-list list="vm.list"></nested-list>
</body>
</code>```

JavaScript

```<code>angular.module('myApp', [])

  .controller('myCtrl', ['$scope', function($scope) {
    $scope.list = [
      { "name": "Item 1" },
      { "name": "Item 2",
        "subItems": [
          { "name": " Item 2.1" }
        ]
      },
      { "name": "Item 3",
        "subItems": [
          { "name": " Item 3.1" },
          { "name": "Item 3.2",
            "subItems": [
              { "name": "Item 3.2.1" },
              { "name": "Item 3.2.2" }
            ]
          }
        ]
    }];
  }])

  .component('nestedList', {
    bindings: {
      list: '<'
    },
    template: `
      <div ng-repeat="item in $ctrl.list" >
        <div> {{item.name}} </div>
        <nested-list list="item.subItems"></nested-list>
      </div>
    `
  });
</code>```

Undoubtedly because I'm missing something obvious, the list from the app's main controller myCtrl isn't getting bound to the root component. If anyone can provide insight, I'd be grateful.

Stephen

答:
As you are using controllerAs, you should be binding values to controller this(context) instead of binding values to $scope.

```<code>.controller('myCtrl', [function() {
    var vm = this;
    vm.list = [ ..];
}]);
</code>```

Plunker Here

Title: Recursive Components in AngularJS 1.x

Body:
Finally trying to learn AngularJS and I can't quite figure out how to make components work recursively. I have a simple example that's not rendering as expected.

HTML

  <nested-list list="vm.list"></nested-list>

JavaScript

angular.module('myApp', [])

  .controller('myCtrl', ['$scope', function($scope) {
    $scope.list = [
      { "name": "Item 1" },
      { "name": "Item 2",
        "subItems": [
          { "name": " Item 2.1" }
        ]
      },
      { "name": "Item 3",
        "subItems": [
          { "name": " Item 3.1" },
          { "name": "Item 3.2",
            "subItems": [
              { "name": "Item 3.2.1" },
              { "name": "Item 3.2.2" }
            ]
          }
        ]
    }];
  }])

  .component('nestedList', {
    bindings: {
      list: '<'
    },
    template: `

 {{item.name}}

        <nested-list list="item.subItems"></nested-list>

    `
  });

Undoubtedly because I'm missing something obvious, the list from the app's main controller myCtrl isn't getting bound to the root component. If anyone can provide insight, I'd be grateful.

Stephen

Body:
As you are using controllerAs, you should be binding values to controller this(context) instead of binding values to $scope.

.controller('myCtrl', [function() {
    var vm = this;
    vm.list = [ ..];
}]);

Plunker Here


问:
Programmatically remove images and videos from html
I'm working on Ruby on Rails 2.3.8 and I've got a website in which users type posts. Each of them has a short description that is shown in the main page. That description is automatically built from the original, but it's just truncated so it reaches a max of 240 characters.

The problem is those descriptions may contain images or videos, and I don't want them to appear when I truncate those strings. I'm using Hpricot plugin to parse HTML, and the following regular expression to parse images:

```<code>body = Hpricot.parse(html_body)
body = body.to_s.gsub(/<img .*?>/, '')
</code>```

This is removing images, but sometimes it leaves a string instead, for example it says "image" or "img" where the image was before. Now, for example, I see a loose "spam" text remaining after I deleted an image from the description. Maybe the regex is not correct.

Does anybody know which is the right regex for removing images, and also videos from html?

答:
It seemn go me that you are searching for img with a space after it.

Don't you want this so that you can grab the <img and everything up to but not including the > and then grab the >?

Hard to say if it works without source input.

```<code><img([^>])+
</code>```

CAUTION: will NOT work with nested tags.

Body:
I'm working on Ruby on Rails 2.3.8 and I've got a website in which users type posts. Each of them has a short description that is shown in the main page. That description is automatically built from the original, but it's just truncated so it reaches a max of 240 characters.

The problem is those descriptions may contain images or videos, and I don't want them to appear when I truncate those strings. I'm using Hpricot plugin to parse HTML, and the following regular expression to parse images:

body = Hpricot.parse(html_body)
body = body.to_s.gsub(//, '')

This is removing images, but sometimes it leaves a string instead, for example it says "image" or "img" where the image was before. Now, for example, I see a loose "spam" text remaining after I deleted an image from the description. Maybe the regex is not correct.

Does anybody know which is the right regex for removing images, and also videos from html?

Body:
It seemn go me that you are searching for img with a space after it.

Don't you want this so that you can grab the <img and everything up to but not including the > and then grab the >?

Hard to say if it works without source input.

<img([^>])+

CAUTION: will NOT work with nested tags.


问:
Get App Id of same type of apps in multiple Podio Workspace
I want to get App Id of same type of apps multiple Podio Work space.

Example scenario: I have two work space. Both work space have Deliverable app. I want to get App Id of Deliverable app of both Work space.

```<code>PodioApp::get_all( $attributes = array() );
</code>```

I can get apps by above api request. But i can't track if it is Deliverable app or not.

答:
If the app in space B is cloned from the app in space A, then the app in space B will have a field called original that will hold the ID of the app in space A.

You can try to clone an app in Podio and then go here https://developers.podio.com/doc/applications/get-app-22349 and fetch the app of the newly cloned app to verify.

```<code> {
   ...
   "app_id": 18245877,
   "original": 18166054,
   ...
 }
</code>```

If you just happen to have constructed 2 apps that share the same fields, then they have no such relation and comparing them is a hell of a harder task.

Body:
I want to get App Id of same type of apps multiple Podio Work space.

Example scenario: I have two work space. Both work space have Deliverable app. I want to get App Id of Deliverable app of both Work space.

PodioApp::get_all( $attributes = array() );

I can get apps by above api request. But i can't track if it is Deliverable app or not.

Body:
If the app in space B is cloned from the app in space A, then the app in space B will have a field called original that will hold the ID of the app in space A.

You can try to clone an app in Podio and then go here https://developers.podio.com/doc/applications/get-app-22349 and fetch the app of the newly cloned app to verify.

 {
   ...
   "app_id": 18245877,
   "original": 18166054,
   ...
 }

If you just happen to have constructed 2 apps that share the same fields, then they have no such relation and comparing them is a hell of a harder task.


问:
Increment value in Postgresql when adding new entry, using jpa/hibernate Spring
I have 2 tables, one is manufacturer and one is monitor, in order to not apply the 1+n queries. I want to be able to increment the number of monitors under each manufacturer:

```<code>    manufacturer table:                      monitor
    id    name     totalMonitors             id     name     manufacturerId

    1     manuf1     100000                  1      mon1     1
    2     manuf2     2000                    2      mon2     2
</code>```

Entity:

```<code>public class Manufacturer{

    private long id;

    private String name;

    private long totalMonitors;
}

public class Monitor{

    private long id;

    private String name;

    private Manufacturer manufacturer;
}
</code>```

I use a DTO to work with the data. I am really puzzled by the way
         you can increment a value in the DB, for the query I will use a DAO interface.

```<code>     @QUERY("Query to get the number of total monitors for each manuf")
     long countByManufacturerId(List<Manufacturer> manufacturers);
</code>```

As this will be a web application i canot count each time the number of monitors in the DB
         because this will lower the performance, what I want to know is if there is a solution
         to trigger an increment of the value "totalMonitors" whenever an operation of add/delete is
         is performed on the DB.

答: Yuo could try looking at JPA Callback annotations. </p>

Body:
I have 2 tables, one is manufacturer and one is monitor, in order to not apply the 1+n queries. I want to be able to increment the number of monitors under each manufacturer:

    manufacturer table:                      monitor
    id    name     totalMonitors             id     name     manufacturerId

    1     manuf1     100000                  1      mon1     1
    2     manuf2     2000                    2      mon2     2

Entity:

public class Manufacturer{

    private long id;

    private String name;

    private long totalMonitors;
}

public class Monitor{

    private long id;

    private String name;

    private Manufacturer manufacturer;
}

I use a DTO to work with the data. I am really puzzled by the way
         you can increment a value in the DB, for the query I will use a DAO interface.

     @QUERY("Query to get the number of total monitors for each manuf")
     long countByManufacturerId(List<Manufacturer> manufacturers);

As this will be a web application i canot count each time the number of monitors in the DB
         because this will lower the performance, what I want to know is if there is a solution
         to trigger an increment of the value "totalMonitors" whenever an operation of add/delete is
         is performed on the DB.