问:
How do I get the bottom of my div to stay fixed after clicking the generator button?
Here is my code

HTML

```<code><head>
<link
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css"
rel="stylesheet"  type='text/css'>
<h1 style="text-align: center; color: red; font-family: verdana; font-
weight: bold;">WHAT CHRISTMAS MOVIE SHOULD I WATCH?</h1>
</head>
<body>
<div class="container">
<div id="generator" style="padding-top: 10px;">
<p>
<i class="fa fa-snowflake-o fa-5x spin"></i>
<i class="fa fa-gift fa-5x spin"></i>
<i class="fa fa-tree fa-5x spin"></i>

</p>

<input type="button" id="btnSearch" value="What Christmas Movie Should I
Watch?" onclick="GetValue();" />
<p id="message"></p>
</div>
</div>
</body>
</code>```

JQUERY

```<code>function GetValue()
{
var myarray= new Array("The Santa Claus","Just Friends","Home Alone", "Home
Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A
Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed
Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet
Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth
1977","Bad Santa");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}

https://codepen.io/McComb/pen/qVPOQO
</code>```

click the button and see how the bottom of the div changes the box shape. How do I avoid this? I just want the bottom line of the box to stay fixed. I am open to different solutions for this. Perhaps placeholder text?

答:
Set a height and max-height on your generator div:</p>

```<code>#generator {
  height: 250px;
  max-height: 250px;
}
</code>```

Body:
Here is my code

HTML

<link
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css"
rel="stylesheet"  type='text/css'>

WHAT CHRISTMAS MOVIE SHOULD I WATCH?

<input type="button" id="btnSearch" value="What Christmas Movie Should I
Watch?" onclick="GetValue();" />

JQUERY

function GetValue()
{
var myarray= new Array("The Santa Claus","Just Friends","Home Alone", "Home
Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A
Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed
Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet
Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth
1977","Bad Santa");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}

https://codepen.io/McComb/pen/qVPOQO

click the button and see how the bottom of the div changes the box shape. How do I avoid this? I just want the bottom line of the box to stay fixed. I am open to different solutions for this. Perhaps placeholder text?

Body:
Set a height and max-height on your generator div:

#generator {
  height: 250px;
  max-height: 250px;
}


来源: stackexchange

问:
Joda time saves invalid date through hibernate
I am having issue storing a date while converting it from String to Date Time.

Below is the code,

```<code>import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

String date1 = "2017-11-02";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

someHibernateMethod.setTransactionDate1(formatter.parseDateTime(date1));
someHibernateMethod.setTransactionDate2(DateTime.now());
</code>```

date1 saved as - "2017-11-01 19:00:00.000", but when I save date with DateTime.Now() it saves correctly.

I am expecting "2017-11-02 00:00:00.000" for date1

答:
Found a solution as below,</p>

```<code>String date1 = "2017-11-02";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate localDate = formatter.parseLocalDate(date1);
DateTime newDate= localDate.toDateTime(new LocalTime());
someHibernateMethod.setTransactionDate1(newDate)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having issue storing a date while converting it from String to Date Time.

Below is the code,

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

String date1 = "2017-11-02";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

someHibernateMethod.setTransactionDate1(formatter.parseDateTime(date1));
someHibernateMethod.setTransactionDate2(DateTime.now());

date1 saved as - "2017-11-01 19:00:00.000", but when I save date with DateTime.Now() it saves correctly.

I am expecting "2017-11-02 00:00:00.000" for date1

Body:
Found a solution as below,

String date1 = "2017-11-02";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate localDate = formatter.parseLocalDate(date1);
DateTime newDate= localDate.toDateTime(new LocalTime());
someHibernateMethod.setTransactionDate1(newDate)


问:
Setup analytics goal where user originated from a particular url
We want to create a checkout goal in Google Analytics that is only triggered when the user came to our site from a specific url.

E.g. our site www.buysomething.com is an ecommerce site that sells 1 product. We want to know how many people completed the purchase after arriving on our site from www.partnersite.com (a 3rd party site we do not own).

Here's an example scenario:
* user goes to partnersite.com
* user clicks a buy now button on partnersite.com
* the user is taken to our website buysomething.com (either in an iframe or a new window)
* the user completes the purchase

We're not interested in how many people bought the item, only how many people came from partnersite.com and purchased the item.

答:
Option 1: Segment

Like Eike mentioned in his comment, you could use a generic goal of all purchases and then segment to that referral source. This would be useful if you need to get historic data from your current analytics.

If you have many different individual referrers that you need to track, this may be the best option.

An alternative to this option would be to create a custom report with a secondary dimension of referrer (you can also filter individual custom reports). This could help if you have multiple individual referrers and don't want to have tons of segments or constantly be editing them.

Option 2: View

Create a new View in your property that filters traffic to only show data from that specific referral. Then, create a goal (same as above) and now not only are your goals specific to that referrer, but all of your reports data will be specific to that referral source. Note: This would only have data after it is created (it would not have historic data like a segment would).

If this referral source is truly that important to the data insight of your website, this is the option I would use. Just keep in mind that this view now needs to be managed in addition to any other reporting views you have on the site.


问:
Problem using the webbrowser control
I am working on scraper and using webbrowser control.
Now I'm navigating pages 1 by 1 in the same control.

but while i do this sometimes the browser start loading other page before the first page has been completely loaded. while sometimes it stop all the execution and no page is url is under progress.

I am using the webBrowser1_DocumentCompleted event to process the document and sometime it is been loaded more than once.

So is there any solution that i can check whether my webbrowser is busy working or has done with browsing.

答:
I've noticed it does document completed multiple times if the page uses frames.

You can get the URL of the loaded page from the WebBrowser1_DocumentCompleted Event Arguments.

If it is the case that there's multiple frames, you could compare URL of WebBrowser1_DocumentCompleted with WebBrowser1.URL

so

```<code>if(e.URL == webBrowser1.url) {
  // The main page is done loading
}
</code>```

Or you can try checking

```<code>WebBrowser1.ReadyState == WebBrowserReadyState.Complete
</code>```

A couple gotchas I've found with the WinForms WebBrowser control are

The DOM you have access to doesn't update when changes are done thru AJAX.

Unless you do some extra work to detect when a new window gets created and put that into a tab, (there's some articles on how to do that, if you need it I can send a link)
pages that open new windows will be started in a new process so you lose the ability to scrape those and they loose the session, so if you're logged into a webpage you'll be logged out in the new window.

ContentLicense: CC BY-SA 2.5

Title: Problem using the webbrowser control

Body:
I've noticed it does document completed multiple times if the page uses frames.

You can get the URL of the loaded page from the WebBrowser1_DocumentCompleted Event Arguments.

If it is the case that there's multiple frames, you could compare URL of WebBrowser1_DocumentCompleted with WebBrowser1.URL

so

if(e.URL == webBrowser1.url) {
  // The main page is done loading
}

Or you can try checking

WebBrowser1.ReadyState == WebBrowserReadyState.Complete

A couple gotchas I've found with the WinForms WebBrowser control are

The DOM you have access to doesn't update when changes are done thru AJAX.

Unless you do some extra work to detect when a new window gets created and put that into a tab, (there's some articles on how to do that, if you need it I can send a link)
pages that open new windows will be started in a new process so you lose the ability to scrape those and they loose the session, so if you're logged into a webpage you'll be logged out in the new window.


问:
Binary Search Tree to Linked List conversion converts only half of the entries
I have a binary search tree:

```<code>                3
               / \
              1   6
                   \
                    17
                   /
                 15
                /  \
               13   15
              /
             6
              \
               12
              /
             9
</code>```

And my function that converts the BST to a linked list where root points to the root of the BST:

```<code>ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);
    }
    if (root->left != NULL)
    {
        head = convertBSTtoLinkedList(root->left);
        head->next = list;
        return head;
    }
    return list;
}
</code>```

I have manually gone over my function for hours now and can't see what I've done wrong. I have verified that I am inputting a correctly made BST. My function to print out the list where head points to the start of the linked list:

```<code>void printList(ListNodePtr head)
{
  while (head->next != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
  printf("%d ",(head->key));
}
</code>```

Although I doubt that this function is incorrect.

My intended output is:

```<code>BST
1 3 6 6 9 12 13 15 15 17
Linked list
1 3 6 6 9 12 13 15 15 17
</code>```

However what comes out is:

```<code>BST
1 3 6 6 9 12 13 15 15 17
Linked list
1 3 6 6 17
</code>```

答:
When you get the leftmost tree, you're cutting off all but the head of the left tree and pointing that to the current node.  You want to walk to the end of that tree and point the end to the current node.

```<code>if (root->left != NULL)
{
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);
    tail = head;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    tail->next = list;
    return head;
}
</code>```

Also, a minor optimization on your print function:

```<code>void printList(ListNodePtr head)
{
  while (head != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
}
</code>```

Body:
I have a binary search tree:

                3
               / \
              1   6
                   \
                    17
                   /
                 15
                /  \
               13   15
              /
             6
              \
               12
              /
             9

And my function that converts the BST to a linked list where root points to the root of the BST:

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);
    }
    if (root->left != NULL)
    {
        head = convertBSTtoLinkedList(root->left);
        head->next = list;
        return head;
    }
    return list;
}

I have manually gone over my function for hours now and can't see what I've done wrong. I have verified that I am inputting a correctly made BST. My function to print out the list where head points to the start of the linked list:

void printList(ListNodePtr head)
{
  while (head->next != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
  printf("%d ",(head->key));
}

Although I doubt that this function is incorrect.

My intended output is:

BST
1 3 6 6 9 12 13 15 15 17
Linked list
1 3 6 6 9 12 13 15 15 17

However what comes out is:

BST
1 3 6 6 9 12 13 15 15 17
Linked list
1 3 6 6 17

Body:
When you get the leftmost tree, you're cutting off all but the head of the left tree and pointing that to the current node.  You want to walk to the end of that tree and point the end to the current node.

if (root->left != NULL)
{
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);
    tail = head;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    tail->next = list;
    return head;
}

Also, a minor optimization on your print function:

void printList(ListNodePtr head)
{
  while (head != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
}


问:
Python Transitions: how to map all possible transitions of an FSM to a graph
I couldn't install pygraphviz on my Windows 10 system so as a workaround I am trying to store the states and transitions of the FSM in a separate graph. For example:

```<code>from transitions import Machine
from graphviz import Digraph

class Matter(object):
    pass

# The states
states=['hungry', 'satisfied', 'full', 'sick']

# And some transitions between states.
transitions = [
     { 'trigger': 'eat', 'source': 'hungry', 'dest': 'satisfied' },
     { 'trigger': 'eat', 'source': 'satisfied', 'dest': 'full' },
     { 'trigger': 'eat', 'source': 'full', 'dest': 'sick' },
     { 'trigger': 'rest', 'source': ['satisfied', 'full', 'sick'], 'dest':
      'hungry' }]

# Initialize
machine = Matter()
fsm = Machine(machine, states=states, transitions=transitions, initial=states[0])
dot = Digraph(comment='FSM')

src = machine.state

for event in transitions:
    machine.trigger(event['trigger'])
    dst = machine.state
    dot.edge(src,dst,event['trigger'])
    src = dst

print (dot)
</code>```

Here my graph doesn't include all the possible transitions and includes only the sequential transitions.

Output:

```<code>digraph {
    hungry -> satisfied [label=eat]
    satisfied -> full [label=eat]
    full -> sick [label=eat]
    sick -> hungry [label=rest]
}
</code>```

As you can see the multiple state transitions are not present in the graph. Is there a way I can trigger all the transitions and store it in the graph or do I have to write a custom code for all of this to work.

答:
transitions organises transitions in events. An Event may contain several transitions, again organised in a dictionary. To achieve what you desire, first iterate over the event dictionary (key is the trigger name and value is the Event itself) to get the events. Then, iterate over Event.transitions (key is the source state and value is a list of applicable Transition objects) to get a list of transitions. Now, iterate over this list to get the source and destination of each transition. You can use the trigger name as a label if you like:

```<code>from transitions import Machine
from graphviz import Digraph

class Matter(object):
    pass

# The states
states = ['hungry', 'satisfied', 'full', 'sick']

# And some transitions between states.
transitions = [{'trigger': 'eat', 'source': 'hungry', 'dest': 'satisfied'},
               {'trigger': 'eat', 'source': 'satisfied', 'dest': 'full'},
               {'trigger': 'eat', 'source': 'full', 'dest': 'sick'},
               {'trigger': 'rest', 'source': ['satisfied', 'full', 'sick'],
                'dest': 'hungry'}]

# Initialize
machine = Matter()
fsm = Machine(machine, states=states, transitions=transitions, initial=states[0],
              auto_transitions=False)
dot = Digraph(comment='FSM')

for label, event in fsm.events.items():
    for event_transitions in event.transitions.values():
        for transition in event_transitions:
            dot.edge(transition.source, transition.dest, label)
print(dot)
</code>```

Output:

```<code>// FSM
digraph {
    hungry -> satisfied [label=eat]
    satisfied -> full [label=eat]
    full -> sick [label=eat]
    satisfied -> hungry [label=rest]
    full -> hungry [label=rest]
    sick -> hungry [label=rest]
}
</code>```

I also added auto_transitions=False to your Machine. This way transitions will not generate auto transitions (to_<state_name>) which would otherwise clutter your graph. Of course, you can tinker with auto_transitions=True or try to filter auto transitions from the graph as done in transitions' diagrams extension.

Body:
I couldn't install pygraphviz on my Windows 10 system so as a workaround I am trying to store the states and transitions of the FSM in a separate graph. For example:

from transitions import Machine
from graphviz import Digraph

class Matter(object):
    pass

# The states
states=['hungry', 'satisfied', 'full', 'sick']

# And some transitions between states.
transitions = [
     { 'trigger': 'eat', 'source': 'hungry', 'dest': 'satisfied' },
     { 'trigger': 'eat', 'source': 'satisfied', 'dest': 'full' },
     { 'trigger': 'eat', 'source': 'full', 'dest': 'sick' },
     { 'trigger': 'rest', 'source': ['satisfied', 'full', 'sick'], 'dest':
      'hungry' }]

# Initialize
machine = Matter()
fsm = Machine(machine, states=states, transitions=transitions, initial=states[0])
dot = Digraph(comment='FSM')

src = machine.state

for event in transitions:
    machine.trigger(event['trigger'])
    dst = machine.state
    dot.edge(src,dst,event['trigger'])
    src = dst

print (dot)

Here my graph doesn't include all the possible transitions and includes only the sequential transitions.

Output:

digraph {
    hungry -> satisfied [label=eat]
    satisfied -> full [label=eat]
    full -> sick [label=eat]
    sick -> hungry [label=rest]
}

As you can see the multiple state transitions are not present in the graph. Is there a way I can trigger all the transitions and store it in the graph or do I have to write a custom code for all of this to work.

Body:
transitions organises transitions in events. An Event may contain several transitions, again organised in a dictionary. To achieve what you desire, first iterate over the event dictionary (key is the trigger name and value is the Event itself) to get the events. Then, iterate over Event.transitions (key is the source state and value is a list of applicable Transition objects) to get a list of transitions. Now, iterate over this list to get the source and destination of each transition. You can use the trigger name as a label if you like:

from transitions import Machine
from graphviz import Digraph

class Matter(object):
    pass

# The states
states = ['hungry', 'satisfied', 'full', 'sick']

# And some transitions between states.
transitions = [{'trigger': 'eat', 'source': 'hungry', 'dest': 'satisfied'},
               {'trigger': 'eat', 'source': 'satisfied', 'dest': 'full'},
               {'trigger': 'eat', 'source': 'full', 'dest': 'sick'},
               {'trigger': 'rest', 'source': ['satisfied', 'full', 'sick'],
                'dest': 'hungry'}]

# Initialize
machine = Matter()
fsm = Machine(machine, states=states, transitions=transitions, initial=states[0],
              auto_transitions=False)
dot = Digraph(comment='FSM')

for label, event in fsm.events.items():
    for event_transitions in event.transitions.values():
        for transition in event_transitions:
            dot.edge(transition.source, transition.dest, label)
print(dot)

Output:

// FSM
digraph {
    hungry -> satisfied [label=eat]
    satisfied -> full [label=eat]
    full -> sick [label=eat]
    satisfied -> hungry [label=rest]
    full -> hungry [label=rest]
    sick -> hungry [label=rest]
}

I also added auto_transitions=False to your Machine. This way transitions will not generate auto transitions (to_<state_name>) which would otherwise clutter your graph. Of course, you can tinker with auto_transitions=True or try to filter auto transitions from the graph as done in transitions' diagrams extension.


问:
How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?
```<code>    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)
</code>```

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

答:
Consider the instance [(1,1), (1,1), (1,1)]
In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:

```<code>new_check = []
for x in check:
   this = sorted(x)
   if x not in new_check:
      new_check.append(x)
return new_check
</code>```

Body:
    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

Body:
Consider the instance [(1,1), (1,1), (1,1)]
In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:

new_check = []
for x in check:
   this = sorted(x)
   if x not in new_check:
      new_check.append(x)
return new_check


问:
Iterating multiple children nodes using Jackson
I'm having trouble iterating this structure. I know there are a few approaches using Jackson and I'm hoping someone could provide a quick and manageable solution.

The JSON structure is consistent throughout and every child will have a "children" field regardless of its size.

I would like to output field1, field 2, and field3 for each node. Hierarchy of the nodes is irrelevant.

```<code>{
    "field1": "example data",
    "field2": "example data2",
    "field3": "example data3",
    "children": [{
        "field1": "example data",
        "field2": "example data2",
        "field3": "example data3",
        "children": [{
                "field1": "example data",
                "field2": "example data2",
                "field3": "example data3",
                "children": []
            },
            {
                "field1": "example data",
                "field2": "example data2",
                "field3": "example data3",
                "children": []
            }
        ]
    }, {
        "field1": "example data",
        "field2": "example data2",
        "field3": "example data3",
        "children": [{
            "field1": "example data",
            "field2": "example data2",
            "field3": "example data3",
            "children": []
        }]
    }]
}
</code>```

答:
The streaming API provides a simple solution:

```<code>JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(json);

while (parser.nextToken() != null) {
    String name = parser.getCurrentName();
    if ("field1".equals(name)) {
        parser.nextToken();                 // Advance to the field value
        String value = parser.getText();    // Get the field value as a string
        System.out.println(value);
    }
}
parser.close();
</code>```

Usually the streaming API requires a lot more work to use, but in this case (because hierarchy isn't important) it seems appropriate.

Body:
I'm having trouble iterating this structure. I know there are a few approaches using Jackson and I'm hoping someone could provide a quick and manageable solution.

The JSON structure is consistent throughout and every child will have a "children" field regardless of its size.

I would like to output field1, field 2, and field3 for each node. Hierarchy of the nodes is irrelevant.

{
    "field1": "example data",
    "field2": "example data2",
    "field3": "example data3",
    "children": [{
        "field1": "example data",
        "field2": "example data2",
        "field3": "example data3",
        "children": [{
                "field1": "example data",
                "field2": "example data2",
                "field3": "example data3",
                "children": []
            },
            {
                "field1": "example data",
                "field2": "example data2",
                "field3": "example data3",
                "children": []
            }
        ]
    }, {
        "field1": "example data",
        "field2": "example data2",
        "field3": "example data3",
        "children": [{
            "field1": "example data",
            "field2": "example data2",
            "field3": "example data3",
            "children": []
        }]
    }]
}

Body:
The streaming API provides a simple solution:

JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(json);

while (parser.nextToken() != null) {
    String name = parser.getCurrentName();
    if ("field1".equals(name)) {
        parser.nextToken();                 // Advance to the field value
        String value = parser.getText();    // Get the field value as a string
        System.out.println(value);
    }
}
parser.close();

Usually the streaming API requires a lot more work to use, but in this case (because hierarchy isn't important) it seems appropriate.


问:
Upgrading from PostGIS 2.1: "Error: attempt to redefine parameter "postgis.backend"
Upgrading from PostGIS 2.1: "Error: attempt to redefine parameter "postgis.backend"

I am trying to upgrade my PostGIS database on AWS RDS, but I am getting an error when running ALTER EXTENSION postgis UPDATE, as shown below:

```<code>my_db=> alter extension postgis update;
ERROR:  attempt to redefine parameter "postgis.backend"
</code>```

And here is some additional information about my database:

```<code>my_db=> select distinct probin from pg_proc where probin like '%postgis%';
-[ RECORD 1 ]-----------------
probin | $libdir/rtpostgis-2.1
-[ RECORD 2 ]-----------------
probin | $libdir/postgis-2.1

my_db=> select version();
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------
version | PostgreSQL 9.5.9 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16), 64-bit

my_db=> select postgis_full_version();
-[ RECORD 1 ]--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
postgis_full_version | POSTGIS="2.1.8 r13780" GEOS="3.5.1-CAPI-1.9.1 r4246" PROJ="Rel. 4.9.2, 08 September 2015" GDAL="GDAL 1.11.5, released 2016/07/01" LIBXML="2.9.1" LIBJSON="UNKNOWN" TOPOLOGY RASTER
</code>```

The closest resource I could find to address this issue was here: http://postgis.17.x6.nabble.com/postgis-backend-and-legacy-functions-td5009743.html although that issue involved referencing multiple PostGIS versions. It seems that I am getting the same error, but my error may have a different cause, because I am only referencing postgis-2.1 and rtpostgis-2.1, as shown above. Any suggestions would be appreciated.

Update
This seems to be an issue related to RDS, where after a minutes I saw that a patch is applied to RDS via the event logs. After the patch is applied, running the alter extension postgis update command successfully upgrade the PostGIS extension. Closing this question for now.

Body:
Upgrading from PostGIS 2.1: "Error: attempt to redefine parameter "postgis.backend"

I am trying to upgrade my PostGIS database on AWS RDS, but I am getting an error when running ALTER EXTENSION postgis UPDATE, as shown below:

my_db=> alter extension postgis update;
ERROR:  attempt to redefine parameter "postgis.backend"

And here is some additional information about my database:

my_db=> select distinct probin from pg_proc where probin like '%postgis%';
-[ RECORD 1 ]-----------------
probin | $libdir/rtpostgis-2.1
-[ RECORD 2 ]-----------------
probin | $libdir/postgis-2.1

my_db=> select version();
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------
version | PostgreSQL 9.5.9 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16), 64-bit

my_db=> select postgis_full_version();
-[ RECORD 1 ]--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
postgis_full_version | POSTGIS="2.1.8 r13780" GEOS="3.5.1-CAPI-1.9.1 r4246" PROJ="Rel. 4.9.2, 08 September 2015" GDAL="GDAL 1.11.5, released 2016/07/01" LIBXML="2.9.1" LIBJSON="UNKNOWN" TOPOLOGY RASTER

The closest resource I could find to address this issue was here: http://postgis.17.x6.nabble.com/postgis-backend-and-legacy-functions-td5009743.html although that issue involved referencing multiple PostGIS versions. It seems that I am getting the same error, but my error may have a different cause, because I am only referencing postgis-2.1 and rtpostgis-2.1, as shown above. Any suggestions would be appreciated.

Update
This seems to be an issue related to RDS, where after a minutes I saw that a patch is applied to RDS via the event logs. After the patch is applied, running the alter extension postgis update command successfully upgrade the PostGIS extension. Closing this question for now.


问:
$(element).val('newvalue') Is Not Reflected in element.outerHTML
I am unable to see the value attribute of input elements when using element.outerHTML.  Problem is with all input types; example HTML:

```<code><input type="text" id="copy-paste-textarea" />
</code>```

Example JavaScript:

```<code><script type="text/javascript">
$('#copy-paste-textarea').on('click', function(e) {
    console.log("Text area's outerHTML???" + this.outerHTML + "|");
        // Output: <input id="copy-paste-textarea" type="text">

    $(this).val('hello!');
    $(this).addClass('world!');

    console.log("Text area's outerHTML???" + this.outerHTML + "|");
        // Output: <input id="copy-paste-textarea" class="world!" type="text">
});
</script>
</code>```

When I run this code above, I see that the change from addClass() is reflected in this.outerHTML, but the change of val() is not.  BUT -- I see that the field is indeed actually being populated with the values.  I want output to be this:

```<code>// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">
</code>```

The html() function produces the same results.  I would like a solution that works on any input type (select, textarea, etc.).

Similar answer here will only work on textareas: Cannot get outerHTML/value of a dynamically added textarea

答:
This is because elements have "properties", which store dynamic information only in memory as expressed by the JavaScript DOM object and they also have "attributes" where the element's actual markup is recorded in memory and is accessible via the HTML parser.

JQuery's .val() method writes data to an in-memory only property.

To get what you want, you must set the value attribute using
JQuery's .attr() method.

The subtle, but important difference between properties and attributes is what contributes to the confusion between JQuery's .prop() and .attr() methods.

$('#copy-paste-textarea').on('click', function(e) {
    console.log("input field's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).attr("value", "hello!");
    $(this).addClass('world!');

    console.log("input field's outerHTML???" + this.outerHTML + "|");
});

// For a textarea, you need to get the content of the tags with .text()
$('textarea').on('click', function(e) {
    console.log("Text area's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).text("value", "hello!");
    $(this).addClass('world');
    console.log("Text area's outerHTML???" + this.outerHTML + "|");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.world {
  background-color:yellow;
}</code>```

<input type="text" id="copy-paste-textarea">

<textarea></textarea>```

Body:
I am unable to see the value attribute of input elements when using element.outerHTML.  Problem is with all input types; example HTML:

<input type="text" id="copy-paste-textarea" />

Example JavaScript:

When I run this code above, I see that the change from addClass() is reflected in this.outerHTML, but the change of val() is not.  BUT -- I see that the field is indeed actually being populated with the values.  I want output to be this:

// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">

The html() function produces the same results.  I would like a solution that works on any input type (select, textarea, etc.).

Similar answer here will only work on textareas: Cannot get outerHTML/value of a dynamically added textarea

Body:
This is because elements have "properties", which store dynamic information only in memory as expressed by the JavaScript DOM object and they also have "attributes" where the element's actual markup is recorded in memory and is accessible via the HTML parser.

JQuery's .val() method writes data to an in-memory only property.

To get what you want, you must set the value attribute using
JQuery's .attr() method.

The subtle, but important difference between properties and attributes is what contributes to the confusion between JQuery's .prop() and .attr() methods.

$('#copy-paste-textarea').on('click', function(e) {
    console.log("input field's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).attr("value", "hello!");
    $(this).addClass('world!');

    console.log("input field's outerHTML???" + this.outerHTML + "|");
});

// For a textarea, you need to get the content of the tags with .text()
$('textarea').on('click', function(e) {
    console.log("Text area's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).text("value", "hello!");
    $(this).addClass('world');
    console.log("Text area's outerHTML???" + this.outerHTML + "|");
});

.world {
  background-color:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="copy-paste-textarea">

<textarea></textarea>


问:
JTable extended from AbtractTableModel is not updating GUI when i add row
This my new MyJtable

```<code>public void addWidget(Book w) {
    datalist.add(w);
    fireTableRowsInserted(datalist.size()-1, datalist.size()-1);

   }
</code>```

calling class

```<code>  MyJtable tv = new MyJtable(a);
        table = new JTable(tv);
        //tv.addWidget(b3);
        JScrollPane pane2 = new JScrollPane(table);
</code>```

button CLick function

```<code> public void actionPerformed(ActionEvent e)
   {
    MyJtable tv1 = new MyJtable();
    Book b3 = new Book ("Java nutshell-299", "Ajfdfdfdingya2") ;
    if("Add".equals(e.getActionCommand()))
  {
  JOptionPane.showMessageDialog(null,"Add button is clicked");
  tv1.addWidget(b3);
  }
</code>```

when i click button then i don't see any GUI chnage but if call

```<code>tv1.addWidget(b3);

   }
</code>```

before , i mean on load then i can see the new book but not on button click

答:
This my new MyJtable

That is wrong. The table should NOT have an addWidget() method.

All updates to the data should be done directly through the TableModel. Then the TableModel will notify the table to repaint itself when the data changes.

You should never access the data storage used by the TableModel outside of the TableModel itself. I gave you a complete solution when you asked your other question yesterday.

Body:
This my new MyJtable

public void addWidget(Book w) {
    datalist.add(w);
    fireTableRowsInserted(datalist.size()-1, datalist.size()-1);

   }

calling class

  MyJtable tv = new MyJtable(a);
        table = new JTable(tv);
        //tv.addWidget(b3);
        JScrollPane pane2 = new JScrollPane(table);

button CLick function

 public void actionPerformed(ActionEvent e)
   {
    MyJtable tv1 = new MyJtable();
    Book b3 = new Book ("Java nutshell-299", "Ajfdfdfdingya2") ;
    if("Add".equals(e.getActionCommand()))
  {
  JOptionPane.showMessageDialog(null,"Add button is clicked");
  tv1.addWidget(b3);
  }

when i click button then i don't see any GUI chnage but if call

tv1.addWidget(b3);

   }

before , i mean on load then i can see the new book but not on button click


问:
How to calculate in which site of a Voronoi diagram a new point is?
I wrote a small script for showing voronoi diagram of M points from this tutorial. I use scipy.spatial.

I Want to give a new point of plane and say this point is in which site of voronoi diagram. Is it possible?

This is my code:

```<code>import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d

N = 70
M = 10

Matrix = [(random.random()*100,random.random()*100)  for x in range(M)]
points = np.array(Matrix)

vor = Voronoi(points)
print(vor.ridge_vertices)

voronoi_plot_2d(vor)
plt.show()
</code>```

答:
By the concept of Voronoi diagram, the cell that new point P belongs to is generated by the closest point to P among the original points. Finding this point is straightforward minimization of distance:

```<code>point_index = np.argmin(np.sum((points - new_point)**2, axis=1))
</code>```

However, you want to find the region. And the regions in vor.regions are not in the same order as vor.points, unfortunately (I don't really understand why since there should be a region for each point).

So I used the following approach:

Find all ridges around the point I want, using vor.ridge_points

Take all of the ridge vertices from these ridges, as a set

Look for the (unique) region with the same set of vertices.

Result:

```<code>M = 15
points = np.random.uniform(0, 100, size=(M, 2))
vor = Voronoi(points)
voronoi_plot_2d(vor)

new_point = [50, 50]
plt.plot(new_point[0], new_point[1], 'ro')

point_index = np.argmin(np.sum((points - new_point)**2, axis=1))
ridges = np.where(vor.ridge_points == point_index)[0]
vertex_set = set(np.array(vor.ridge_vertices)[ridges, :].ravel())
region = [x for x in vor.regions if set(x) == vertex_set][0]

polygon = vor.vertices[region]
plt.fill(*zip(*polygon), color='yellow')
plt.show()
</code>```

Here is a demo:

Note that the coloring of the region will be incorrect if it is unbounded; this is a flaw of the simple-minded coloring approach, not of the region-finding algorithm. See Colorize Voronoi Diagram for the correct way to color unbounded regions.

Aside: I used NumPy to generate random numbers, which is simpler than what you did.

Body:
I wrote a small script for showing voronoi diagram of M points from this tutorial. I use scipy.spatial.

I Want to give a new point of plane and say this point is in which site of voronoi diagram. Is it possible?

This is my code:

import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d

N = 70
M = 10

Matrix = [(random.random()*100,random.random()*100)  for x in range(M)]
points = np.array(Matrix)

vor = Voronoi(points)
print(vor.ridge_vertices)

voronoi_plot_2d(vor)
plt.show()

Body:
By the concept of Voronoi diagram, the cell that new point P belongs to is generated by the closest point to P among the original points. Finding this point is straightforward minimization of distance:

point_index = np.argmin(np.sum((points - new_point)**2, axis=1))

However, you want to find the region. And the regions in vor.regions are not in the same order as vor.points, unfortunately (I don't really understand why since there should be a region for each point).

So I used the following approach:

Find all ridges around the point I want, using vor.ridge_points

Take all of the ridge vertices from these ridges, as a set

Look for the (unique) region with the same set of vertices.

Result:

M = 15
points = np.random.uniform(0, 100, size=(M, 2))
vor = Voronoi(points)
voronoi_plot_2d(vor)

new_point = [50, 50]
plt.plot(new_point[0], new_point[1], 'ro')

point_index = np.argmin(np.sum((points - new_point)**2, axis=1))
ridges = np.where(vor.ridge_points == point_index)[0]
vertex_set = set(np.array(vor.ridge_vertices)[ridges, :].ravel())
region = [x for x in vor.regions if set(x) == vertex_set][0]

polygon = vor.vertices[region]
plt.fill(*zip(*polygon), color='yellow')
plt.show()

Here is a demo:

Note that the coloring of the region will be incorrect if it is unbounded; this is a flaw of the simple-minded coloring approach, not of the region-finding algorithm. See Colorize Voronoi Diagram for the correct way to color unbounded regions.

Aside: I used NumPy to generate random numbers, which is simpler than what you did.


问:
Run scripts simultaniously in Canopy
This is an update request on this 4 year old question.

I have been using Canopy for many years but one draw back is that I can't debug a different project while another is running. I often run code that takes about an hour so it would be ideal to be able to run one project while working on another. In short, I would like to use multiple kernels integrated with the IDE. Perhaps as many as three as I have four cores.

Canopy is my default an only python on my windows machine. I am using Canopy 2.1.3 with python 3.5

答:
The use-case is clear, but is not yet implemented, though it is getting closer. (Canopy 2.1 can work with multiple different environments, but not yet simultaneously.) I do expect multiple simultaneous running kernels to be available in 2018. Meanwhile, the workaround is the same as before -- develop and test your code in the Canopy GUI, but run your long production runs in Canopy Command Prompts using qtconsole or ipython or plain python.

The current version of Canopy is 2.1.6

FWIW: as a feature request, I'm not sure that this is really an SO-question.

Title: Run scripts simultaniously in Canopy


问:
How to read the csv and convert to RDD in sparkR
As i am a R programmer i want to use R as a interface to spark, with the sparkR package i installed sparkR in R.

I'm new to sparkR. I want to perform some operations on particular data in a CSV record.  I'm trying to read a csv file and convert it to rdd.

```<code>This is the code i did:
sc <- sparkR.init(master="local") # created spark content
data <- read.csv(sc, "/home/data1.csv")
#It throws an error, to use read.table

Data i have to load and convert - http://i.stack.imgur.com/sj78x.png

if am wrong, how to read this data in csv and convert to RDD in sparkR
</code>```

TIA

答:
In the recent SparkR version (2.0+)

```<code>read.df(path, source = "csv")
</code>```

In Spark 1.x

```<code>read.df(sc, path, source = "com.databricks.spark.csv")
</code>```

with

```<code>spark.jars.packages  com.databricks:spark-csv_2.10:1.4.0
</code>```

Body:
As i am a R programmer i want to use R as a interface to spark, with the sparkR package i installed sparkR in R.

I'm new to sparkR. I want to perform some operations on particular data in a CSV record.  I'm trying to read a csv file and convert it to rdd.

This is the code i did:
sc <- sparkR.init(master="local") # created spark content
data <- read.csv(sc, "/home/data1.csv")
#It throws an error, to use read.table

Data i have to load and convert - http://i.stack.imgur.com/sj78x.png

if am wrong, how to read this data in csv and convert to RDD in sparkR

TIA

Body:
In the recent SparkR version (2.0+)

read.df(path, source = "csv")

In Spark 1.x

read.df(sc, path, source = "com.databricks.spark.csv")

with

spark.jars.packages  com.databricks:spark-csv_2.10:1.4.0


问:
Best way to put a embedded video next to text
I had several attempts at doing this, but just couldn't get it quite right. I want the video to be responsive when the browser shrinks and eventually stack when the browser gets small enough, like if it were an image that I put into a bootstrap grid, but I cannot figure out how to do this with an embedded video. Here is my html. I really need help with the css.

```<code><section class="section1">
  <div class="container-fluid">
    <div class="row section1Row">
      <div class="col-md-6 section1Text">
        <h2 class="text-center">What We Have to Offer</h2>
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p>
      </div>
      <div class="video-responsive">
        <iframe width="672" height="378" src="https://www.youtube.com/embed/bsY2GdBEvSA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</section>
</code>```

答:
To get a responsive design you want to mess with CSS media queries : using media queries - MDN. Also, read the full Google Web Fundamentals course, it will help.

TL;DR

Choose your breakpoints (choosing breakpoint):

Don’t use popular screen sizes for breakpoints

Choose content-driven breakpoints

Use CSS @media (max-width: 800px) { ... }

Target media types (media types) or features (media features)

Test media queries: testing media queries - MDN

Mess with flex-direction: row

Body:
I had several attempts at doing this, but just couldn't get it quite right. I want the video to be responsive when the browser shrinks and eventually stack when the browser gets small enough, like if it were an image that I put into a bootstrap grid, but I cannot figure out how to do this with an embedded video. Here is my html. I really need help with the css.

What We Have to Offer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.


问:
Stackoverflow exception in a PersistentFSM actor
Here is the code:

```<code>import akka.actor.{ActorSystem, Props}
import akka.persistence.fsm.PersistentFSM
import akka.persistence.fsm.PersistentFSM.FSMState

import scala.reflect._
import scala.reflect.ClassTag

/**
  * Created by IDEA on 4/4/16.
  */

object Vendor {

  sealed trait State extends FSMState

  case object Dumb extends State {
    override def identifier = "dumb-state"
  }

  case object Smart extends State {
    override def identifier = "smart-state"
  }

  val prices = Map(
    "cola-light" -> 1.23,
    "cola-fanta" -> 1.23,
    "cola" -> 1.23,
    "lays-natural" -> 3.92,
    "lays-paprika" -> 3.24,
    "lays-mix" -> 2.56,
    "lays-superchips" -> 3.99
  )

  case class Data(var userBalance: Double, val stock: collection.mutable.Map[String, Int])

  sealed trait DomainEvent

  case class DoTransaction(item: String, amount: Int, change: Double) extends DomainEvent

  case class StoreTransaction(credit: Double, reason: String) extends DomainEvent

  case object DoReturnMoney extends DomainEvent

  case class Reject(reason: String) extends DomainEvent

  sealed trait Msg

  case class Transaction(item: String, amount: Int, input: Double) extends Msg

  case object ToggleSmart extends Msg

  case object ReturnMoney extends Msg

}

class Vendor extends PersistentFSM[Vendor.State, Vendor.Data, Vendor.DomainEvent] {

  import Vendor._

  val initData = Data(0d, collection.mutable.Map(
    "cola-light" -> 10,
    "cola-fanta" -> 10,
    "cola" -> 10,
    "lays-natural" -> 10,
    "lays-paprika" -> 10,
    "lays-mix" -> 10,
    "lays-superchips" -> 10
  ))

  override implicit def domainEventClassTag: ClassTag[DomainEvent] = classTag[DomainEvent]

  override def applyEvent(domainEvent: DomainEvent, currentData: Data): Data = {
    domainEvent match {
      case DoTransaction(item, amount, change) =>
        val (verb, suffix) = if (amount > 1) ("are", "s") else ("is", "")
        val changeInfo = if (change > 0) {
          s"And here is your change: €${change}. "
        } else ""
        println(s"Here $verb $amount item$suffix of $item. ${changeInfo}Thanks!")
        currentData.stock(item) -= amount
        currentData.userBalance = 0
        currentData

      case StoreTransaction(credit, reason: String) =>
        println(s"Transaction not successful. \n${reason}\n€${credit} stored on your balance.")
        currentData.userBalance += credit
        currentData

      case DoReturnMoney =>
        println(s"Here is your money: €${currentData.userBalance}.")
        currentData.userBalance = 0
        currentData

      case Reject(reason) =>
        println(s"Transaction rejected due to this reason: $reason")
        currentData
    }
  }

  startWith(Dumb, initData)

  when(Dumb) {
    case Event(Transaction(item, amount, input), currentData) =>
      if (input <= 0) {
        stay applying Reject("you didn't put in money.")
      }
      if (!currentData.stock.contains(item)) {
        val reason = s"We don't have ${item}."
        stay applying StoreTransaction(input, reason)
      }
      if (currentData.stock(item) < amount) {
        val reason = s"We have only ${currentData.stock(item)} ${item} in stock."
        stay applying StoreTransaction(input, reason)
      }
      val change = input + currentData.userBalance - prices(item) * amount
      if (change >= 0) {
        stay applying DoTransaction(item, amount, change)
      } else {
        val reason = s"Insufficient credit, €${-change} in short."
        stay applying StoreTransaction(input, reason)
      }

    case Event(ReturnMoney, _) =>
      stay applying DoReturnMoney

    case Event(ToggleSmart, _) =>
      goto(Smart)
  }

  when(Smart) {
    case Event(Transaction(item, amount, input), currentData) =>
      if (input <= 0) {
        stay applying Reject("you didn't put in money.")
      }
      if (!currentData.stock.contains(item)) {
        val suggestion = currentData.stock.keys.find(x => x.startsWith(item))
        suggestion match {
          case None =>
            stay applying StoreTransaction(input, s"We can't find anything similar to ${item}")
          case Some(item1) =>
            self ! Transaction(item1, amount, input)
        }
      }
      if (currentData.stock(item) < amount) {
        val reason = s"We have only ${currentData.stock(item)} ${item} in stock."
        stay applying StoreTransaction(input, reason)
      }
      val change = input + currentData.userBalance - prices(item) * amount
      if (change >= 0) {
        stay applying DoTransaction(item, amount, change)
      } else {
        val reason = s"Insufficient credit, €${-change} in short."
        stay applying StoreTransaction(input, reason)
      }

    case Event(ReturnMoney, _) =>
      stay applying DoReturnMoney

    case Event(ToggleSmart, _) =>
      goto(Dumb)

  }

  override def persistenceId: String = "persistence-vendor"
}

object VendorApp extends App {
  import Vendor._
  val asys = ActorSystem("persistence-vendor-app")
  val vendor = asys.actorOf(Props[Vendor])
  vendor ! Transaction("cola-light", 2, 5)
  Thread.sleep(1000)
  asys.terminate()
}
</code>```

Here is the error:

```<code>/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/bin/java -Didea.launcher.port=7532 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/tools.jar:/Users/kaiyin/IdeaProjects/Learning Akka (video) code/section4/persistent-fsm&query/target/scala-2.11/classes:/Users/kaiyin/.ivy2/cache/com.google.guava/guava/bundles/guava-16.0.1.jar:/Users/kaiyin/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.11.7.jar:/Users/kaiyin/.ivy2/cache/org.reactivestreams/reactive-streams/jars/reactive-streams-1.0.0.jar:/Users/kaiyin/.ivy2/cache/org.iq80.leveldb/leveldb-api/jars/leveldb-api-0.7.jar:/Users/kaiyin/.ivy2/cache/org.iq80.leveldb/leveldb/jars/leveldb-0.7.jar:/Users/kaiyin/.ivy2/cache/org.fusesource.leveldbjni/leveldbjni-all/bundles/leveldbjni-all-1.8.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-testkit_2.11/jars/akka-testkit_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-stream-experimental_2.11/jars/akka-stream-experimental_2.11-1.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-protobuf_2.11/jars/akka-protobuf_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-persistence_2.11/jars/akka-persistence_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-persistence-query-experimental_2.11/jars/akka-persistence-query-experimental_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-actor_2.11/jars/akka-actor_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe/config/bundles/config-1.3.0.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain VendorApp
Uncaught error from thread [persistence-vendor-app-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[persistence-vendor-app]
java.lang.StackOverflowError
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)

  ...

Process finished with exit code 255
</code>```

build.sbt:

```<code>name := "Persistence"

version := "1.0"

scalaVersion := "2.11.7"

sbtVersion := "0.13.5"

libraryDependencies ++= Seq(
    "com.typesafe.akka"           %% "akka-actor"       % "2.4.0",
    "com.typesafe.akka"           %% "akka-persistence" % "2.4.0",
    "org.iq80.leveldb"            % "leveldb"           % "0.7",
    "org.fusesource.leveldbjni"   % "leveldbjni-all"    % "1.8",
    "com.typesafe.akka" %% "akka-persistence-query-experimental" % "2.4.0",
    "com.typesafe.akka" % "akka-stream-experimental_2.11" % "1.0
</code>```

application.conf:

```<code>akka {
  persistence {
    journal {
      plugin = "akka.persistence.journal.leveldb",
      leveldb {
        dir = "target/example/journal",
        native = false
      }
    },
    snapshot-store {
      plugin = "akka.persistence.snapshot-store.local",
      local {
        dir = "target/example/snapshots"
      }
    }
  }
}
</code>```

Any idea what went wrong?

答:
Instead of

```<code>override implicit def domainEventClassTag: ClassTag[DomainEvent] classTag[DomainEvent]
</code>```

it should be

```<code>override def domainEventClassTag: ClassTag[DomainEvent] = classTag[DomainEvent]
</code>```

Body:
Here is the code:

import akka.actor.{ActorSystem, Props}
import akka.persistence.fsm.PersistentFSM
import akka.persistence.fsm.PersistentFSM.FSMState

import scala.reflect._
import scala.reflect.ClassTag

/**
  * Created by IDEA on 4/4/16.
  */

object Vendor {

  sealed trait State extends FSMState

  case object Dumb extends State {
    override def identifier = "dumb-state"
  }

  case object Smart extends State {
    override def identifier = "smart-state"
  }

  val prices = Map(
    "cola-light" -> 1.23,
    "cola-fanta" -> 1.23,
    "cola" -> 1.23,
    "lays-natural" -> 3.92,
    "lays-paprika" -> 3.24,
    "lays-mix" -> 2.56,
    "lays-superchips" -> 3.99
  )

  case class Data(var userBalance: Double, val stock: collection.mutable.Map[String, Int])

  sealed trait DomainEvent

  case class DoTransaction(item: String, amount: Int, change: Double) extends DomainEvent

  case class StoreTransaction(credit: Double, reason: String) extends DomainEvent

  case object DoReturnMoney extends DomainEvent

  case class Reject(reason: String) extends DomainEvent

  sealed trait Msg

  case class Transaction(item: String, amount: Int, input: Double) extends Msg

  case object ToggleSmart extends Msg

  case object ReturnMoney extends Msg

}

class Vendor extends PersistentFSM[Vendor.State, Vendor.Data, Vendor.DomainEvent] {

  import Vendor._

  val initData = Data(0d, collection.mutable.Map(
    "cola-light" -> 10,
    "cola-fanta" -> 10,
    "cola" -> 10,
    "lays-natural" -> 10,
    "lays-paprika" -> 10,
    "lays-mix" -> 10,
    "lays-superchips" -> 10
  ))

  override implicit def domainEventClassTag: ClassTag[DomainEvent] = classTag[DomainEvent]

  override def applyEvent(domainEvent: DomainEvent, currentData: Data): Data = {
    domainEvent match {
      case DoTransaction(item, amount, change) =>
        val (verb, suffix) = if (amount > 1) ("are", "s") else ("is", "")
        val changeInfo = if (change > 0) {
          s"And here is your change: €${change}. "
        } else ""
        println(s"Here $verb $amount item$suffix of $item. ${changeInfo}Thanks!")
        currentData.stock(item) -= amount
        currentData.userBalance = 0
        currentData

      case StoreTransaction(credit, reason: String) =>
        println(s"Transaction not successful. \n${reason}\n€${credit} stored on your balance.")
        currentData.userBalance += credit
        currentData

      case DoReturnMoney =>
        println(s"Here is your money: €${currentData.userBalance}.")
        currentData.userBalance = 0
        currentData

      case Reject(reason) =>
        println(s"Transaction rejected due to this reason: $reason")
        currentData
    }
  }

  startWith(Dumb, initData)

  when(Dumb) {
    case Event(Transaction(item, amount, input), currentData) =>
      if (input <= 0) {
        stay applying Reject("you didn't put in money.")
      }
      if (!currentData.stock.contains(item)) {
        val reason = s"We don't have ${item}."
        stay applying StoreTransaction(input, reason)
      }
      if (currentData.stock(item) < amount) {
        val reason = s"We have only ${currentData.stock(item)} ${item} in stock."
        stay applying StoreTransaction(input, reason)
      }
      val change = input + currentData.userBalance - prices(item) * amount
      if (change >= 0) {
        stay applying DoTransaction(item, amount, change)
      } else {
        val reason = s"Insufficient credit, €${-change} in short."
        stay applying StoreTransaction(input, reason)
      }

    case Event(ReturnMoney, _) =>
      stay applying DoReturnMoney

    case Event(ToggleSmart, _) =>
      goto(Smart)
  }

  when(Smart) {
    case Event(Transaction(item, amount, input), currentData) =>
      if (input <= 0) {
        stay applying Reject("you didn't put in money.")
      }
      if (!currentData.stock.contains(item)) {
        val suggestion = currentData.stock.keys.find(x => x.startsWith(item))
        suggestion match {
          case None =>
            stay applying StoreTransaction(input, s"We can't find anything similar to ${item}")
          case Some(item1) =>
            self ! Transaction(item1, amount, input)
        }
      }
      if (currentData.stock(item) < amount) {
        val reason = s"We have only ${currentData.stock(item)} ${item} in stock."
        stay applying StoreTransaction(input, reason)
      }
      val change = input + currentData.userBalance - prices(item) * amount
      if (change >= 0) {
        stay applying DoTransaction(item, amount, change)
      } else {
        val reason = s"Insufficient credit, €${-change} in short."
        stay applying StoreTransaction(input, reason)
      }

    case Event(ReturnMoney, _) =>
      stay applying DoReturnMoney

    case Event(ToggleSmart, _) =>
      goto(Dumb)

  }

  override def persistenceId: String = "persistence-vendor"
}

object VendorApp extends App {
  import Vendor._
  val asys = ActorSystem("persistence-vendor-app")
  val vendor = asys.actorOf(Props[Vendor])
  vendor ! Transaction("cola-light", 2, 5)
  Thread.sleep(1000)
  asys.terminate()
}

Here is the error:

/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/bin/java -Didea.launcher.port=7532 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_72.jdk/Contents/Home/lib/tools.jar:/Users/kaiyin/IdeaProjects/Learning Akka (video) code/section4/persistent-fsm&query/target/scala-2.11/classes:/Users/kaiyin/.ivy2/cache/com.google.guava/guava/bundles/guava-16.0.1.jar:/Users/kaiyin/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.11.7.jar:/Users/kaiyin/.ivy2/cache/org.reactivestreams/reactive-streams/jars/reactive-streams-1.0.0.jar:/Users/kaiyin/.ivy2/cache/org.iq80.leveldb/leveldb-api/jars/leveldb-api-0.7.jar:/Users/kaiyin/.ivy2/cache/org.iq80.leveldb/leveldb/jars/leveldb-0.7.jar:/Users/kaiyin/.ivy2/cache/org.fusesource.leveldbjni/leveldbjni-all/bundles/leveldbjni-all-1.8.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-testkit_2.11/jars/akka-testkit_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-stream-experimental_2.11/jars/akka-stream-experimental_2.11-1.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-protobuf_2.11/jars/akka-protobuf_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-persistence_2.11/jars/akka-persistence_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-persistence-query-experimental_2.11/jars/akka-persistence-query-experimental_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe.akka/akka-actor_2.11/jars/akka-actor_2.11-2.4.0.jar:/Users/kaiyin/.ivy2/cache/com.typesafe/config/bundles/config-1.3.0.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain VendorApp
Uncaught error from thread [persistence-vendor-app-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[persistence-vendor-app]
java.lang.StackOverflowError
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)
  at Vendor.domainEventClassTag(Vendor.scala:70)

  ...

Process finished with exit code 255

build.sbt:

name := "Persistence"

version := "1.0"

scalaVersion := "2.11.7"

sbtVersion := "0.13.5"

libraryDependencies ++= Seq(
    "com.typesafe.akka"           %% "akka-actor"       % "2.4.0",
    "com.typesafe.akka"           %% "akka-persistence" % "2.4.0",
    "org.iq80.leveldb"            % "leveldb"           % "0.7",
    "org.fusesource.leveldbjni"   % "leveldbjni-all"    % "1.8",
    "com.typesafe.akka" %% "akka-persistence-query-experimental" % "2.4.0",
    "com.typesafe.akka" % "akka-stream-experimental_2.11" % "1.0

application.conf:

akka {
  persistence {
    journal {
      plugin = "akka.persistence.journal.leveldb",
      leveldb {
        dir = "target/example/journal",
        native = false
      }
    },
    snapshot-store {
      plugin = "akka.persistence.snapshot-store.local",
      local {
        dir = "target/example/snapshots"
      }
    }
  }
}

Any idea what went wrong?

Body:
Instead of

override implicit def domainEventClassTag: ClassTag[DomainEvent] classTag[DomainEvent]

it should be

override def domainEventClassTag: ClassTag[DomainEvent] = classTag[DomainEvent]


问:
Write file to location other than SDcard using Android NDK?
Is there any other way to write a file somewhere else than on the SD card?

I tried many different path on the filesystem but fopen always return NULL, except for any file that I write/read inside the /sdcard/...

Is there something else equivalent to:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

That allow you to write like on the file system or something?

答: You have access to two locations from within your app, the SDCard and a special data directory for your app.  Any other place is off limits unless you have root access.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there any other way to write a file somewhere else than on the SD card?

I tried many different path on the filesystem but fopen always return NULL, except for any file that I write/read inside the /sdcard/...

Is there something else equivalent to:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

That allow you to write like on the file system or something?


问:
How to get `Cloud Functions shell` work with Firestore
Running:

```<code>firebase experimental:functions:shell
</code>```

When I try to call my function like so:

```<code>sendEmail('data', {params: 'commentId:12'})
</code>```

I get:

Info: Function crashed
TypeError: Cannot use 'in' operator to search for 'exists' in data

How does one initiate the new onWrite on a Firestore triggered cloud function

答: With version 3.15.1 of the Firebase CLI, you can now run Firestore functions locally.</p>

Body:
Running:

firebase experimental:functions:shell

When I try to call my function like so:

sendEmail('data', {params: 'commentId:12'})

I get:

Info: Function crashed
TypeError: Cannot use 'in' operator to search for 'exists' in data

How does one initiate the new onWrite on a Firestore triggered cloud function


问:
What can one do in a SQL SUM expr?
The documentation for the SQL SUM function lists its "signature" like this:

```<code>SUM([DISTINCT] expr)
</code>```

The only examples listed for expr are single column names (like units, price, etc.), but can one do more with it? expr sounds very broad and open...

I'm especially interested in if it's possible to do any sort of selection of what exactly to sum. For example, I'd really like to do the following right now:

```<code>SELECT
    SUM(hours) 'Hours total',
    SUM(hours WHERE date BETWEEN '2017-10-01' AND '2017-10-31') 'Hours last month'
</code>```

But that doesn't run... Probably too much of an expr dream, but maybe...? Maybe not?

Is anything like that possible with the SUM function? What can expr be?

答:
Maybe you could use query like:</p>

```<code>SELECT
SUM(hours) 'Hours total',
SUM( CASE WHEN date BETWEEN '2017-10-01' AND '2017-10-31'
THEN hours
ELSE 0 END) 'Hours last month'
from table
</code>```

Title: What can one do in a SQL SUM expr?

Body:
The documentation for the SQL SUM function lists its "signature" like this:

SUM([DISTINCT] expr)

The only examples listed for expr are single column names (like units, price, etc.), but can one do more with it? expr sounds very broad and open...

I'm especially interested in if it's possible to do any sort of selection of what exactly to sum. For example, I'd really like to do the following right now:

SELECT
    SUM(hours) 'Hours total',
    SUM(hours WHERE date BETWEEN '2017-10-01' AND '2017-10-31') 'Hours last month'

But that doesn't run... Probably too much of an expr dream, but maybe...? Maybe not?

Is anything like that possible with the SUM function? What can expr be?

Body:
Maybe you could use query like:

SELECT
SUM(hours) 'Hours total',
SUM( CASE WHEN date BETWEEN '2017-10-01' AND '2017-10-31'
THEN hours
ELSE 0 END) 'Hours last month'
from table


问:
Exposing Inline function vs declared function in service AngularJS
I'm having trouble understanding why the follow code doesn't work.

index.html

```<code><html>
<head lang="en">
    <script src="../Scripts/angular.js"></script>
    <script src="app/books/BooksController.js"></script>
    <script src="app/services/dataService.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="BooksController as vm">
        <h3>All Books</h3>

        <div>
            <ul>
                <li ng-repeat="book in vm.allBooks">
                    {{ book.title }} - {{ book.author }}
                </li>
            </ul>
        </div>
    </div>

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

BookController.js

```<code>(function() {

  var app = angular.module('app', []);

  var BooksController = function(dataService) {
    var vm = this;

    vm.allBooks = dataService.getAllBooks;

  }

  app.controller('BooksController', ["dataService", BooksController]);
})();
</code>```

dataService.js

```<code>(function() {

  var app = angular.module('app');

  var dataService = function() {

    return {
      getAllBooks: getAllBooks
    };

    var getAllBooks = function() {
      return [{
          book_id: 1,
          title: "Harry Pptter and the Deathly Hallows",
          author: "J.K. Rowling",
          year_published: 2000
        },
        {
          book_id: 2,
          title: "The Cat in the Hat",
          author: "Dr. Seuss",
          year_published: 1957
        },
        {
          book_id: 3,
          title: "Encyclopedia Brown, Boy Detective",
          author: "Donald J. Sobol",
          year_published: 1963
        }
      ];
    };
  }

  app.factory('dataService', dataService);
})();
</code>```

The problem seems to be when I expose the methods through the service using:

```<code>return {
    getAllBooks: getAllBooks
};
</code>```

If I change the declaration of the function getAllBooks to look like this,

```<code>function getAllBooks() {
    ...
}
</code>```

and call the service in my controller as:

```<code>vm.allBooks = dataService.getAllBooks()
</code>```

It'll work fine.

My question is, why doesn't it work for declare functions and putting them in variables? Is it because the function is only defined, but not actually executed?

答:
This is because function expression is not hoisted, and function declaration is hoisted.

You just need to put return statement after the function expression.

So put this return statement after the function expression

```<code>return {
    getAllBooks: getAllBooks
};
</code>```

Explanation

In javascript functions can be hoisted, which means you can use them before declaring them.

But this is limited to function declarations only, not function expressions.

Function declaration example:

```<code>testFunction();//this will print this function is hoisted
function testFunction(){
 console.log("this function is hoisted");
}
</code>```

Function expression example:

```<code>testFunction(); //Error because testFunction expression is not hoisted
var testFunction = function(){
 //this functions is not hoisted
}
</code>```

For more information about hoisting these two links are really helpful
https://scotch.io/tutorials/understanding-hoisting-in-javascript
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html

Body:
I'm having trouble understanding why the follow code doesn't work.

index.html

All Books

                    {{ book.title }} - {{ book.author }}

BookController.js

(function() {

  var app = angular.module('app', []);

  var BooksController = function(dataService) {
    var vm = this;

    vm.allBooks = dataService.getAllBooks;

  }

  app.controller('BooksController', ["dataService", BooksController]);
})();

dataService.js

(function() {

  var app = angular.module('app');

  var dataService = function() {

    return {
      getAllBooks: getAllBooks
    };

    var getAllBooks = function() {
      return [{
          book_id: 1,
          title: "Harry Pptter and the Deathly Hallows",
          author: "J.K. Rowling",
          year_published: 2000
        },
        {
          book_id: 2,
          title: "The Cat in the Hat",
          author: "Dr. Seuss",
          year_published: 1957
        },
        {
          book_id: 3,
          title: "Encyclopedia Brown, Boy Detective",
          author: "Donald J. Sobol",
          year_published: 1963
        }
      ];
    };
  }

  app.factory('dataService', dataService);
})();

The problem seems to be when I expose the methods through the service using:

return {
    getAllBooks: getAllBooks
};

If I change the declaration of the function getAllBooks to look like this,

function getAllBooks() {
    ...
}

and call the service in my controller as:

vm.allBooks = dataService.getAllBooks()

It'll work fine.

My question is, why doesn't it work for declare functions and putting them in variables? Is it because the function is only defined, but not actually executed?

Body:
This is because function expression is not hoisted, and function declaration is hoisted.

You just need to put return statement after the function expression.

So put this return statement after the function expression

return {
    getAllBooks: getAllBooks
};

Explanation

In javascript functions can be hoisted, which means you can use them before declaring them.

But this is limited to function declarations only, not function expressions.

Function declaration example:

testFunction();//this will print this function is hoisted
function testFunction(){
 console.log("this function is hoisted");
}

Function expression example:

testFunction(); //Error because testFunction expression is not hoisted
var testFunction = function(){
 //this functions is not hoisted
}

For more information about hoisting these two links are really helpful
https://scotch.io/tutorials/understanding-hoisting-in-javascript
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html


问:
Looking for an If statement to check to see if a user is a local administrator
Currently very noobish with powershell but learning my way around. Looking to make a script that checks to see if the user is apart of the local admin group. Currently what I have will check if the account is created and will create it and set the password and group.

```<code>#add administrator account to local machine and add to administrator group

if (Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='administrator'")

{
    Write-Host "Account already exists"
    Write-Host "Skipping account creation of local account administrator"

}

else

{
    Write-Host "creating Local Admin Account"
    Write-Host "Please Set the password for the Local Admin account to create it"
    $Password = Read-Host -AsSecureString
    New-LocalUser "Administrator" -Password $Password -FullName "Help Desk Administrator" -Description "Local Admin account"
    Add-LocalGroupMember -Group Administrators -Member administrator
    Write-Host "account administrator created"
}
</code>```

However I need error checking to make sure that if the account already exists that is part of the admin group.

the current state of local admins on machines here is a mess

答:
If you are looking to find out if the current user is elevated, here are two ways in PowerShell:

Use #requires -RunAsAdministrator. This will prevent your script from running if the current user is not elevated. This requires PowerShell 3.0 or later.

Ask the system at runtime if the current user is elevated; e.g.:

```<code>$elevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
</code>```

If you are looking for a way to manage the membership of the Administrators group, then that is a different question. Usually I recommend Group Policy for that.

Body:
Currently very noobish with powershell but learning my way around. Looking to make a script that checks to see if the user is apart of the local admin group. Currently what I have will check if the account is created and will create it and set the password and group.

#add administrator account to local machine and add to administrator group

if (Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='administrator'")

{
    Write-Host "Account already exists"
    Write-Host "Skipping account creation of local account administrator"

}

else

{
    Write-Host "creating Local Admin Account"
    Write-Host "Please Set the password for the Local Admin account to create it"
    $Password = Read-Host -AsSecureString
    New-LocalUser "Administrator" -Password $Password -FullName "Help Desk Administrator" -Description "Local Admin account"
    Add-LocalGroupMember -Group Administrators -Member administrator
    Write-Host "account administrator created"
}

However I need error checking to make sure that if the account already exists that is part of the admin group.

the current state of local admins on machines here is a mess

Body:
If you are looking to find out if the current user is elevated, here are two ways in PowerShell:

Use #requires -RunAsAdministrator. This will prevent your script from running if the current user is not elevated. This requires PowerShell 3.0 or later.

Ask the system at runtime if the current user is elevated; e.g.:

$elevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

If you are looking for a way to manage the membership of the Administrators group, then that is a different question. Usually I recommend Group Policy for that.


问:
ASP.Net MVC List of Checkboxes
I am passing a model to a view, which containt a List of items. A DefaultCategories has an id (int), a description (string), and a selected boolean property.

I need to list these items, with a checkbox, and check the ones where the selected property is true.

So, I was trying this:

```<code>    <h1>
        Assigned Categories</h1>
    <table>
        <%foreach (var cat in Model.DefaultCategories)
{%>
        <tr>
            <td>
                <%=cat.Category %>
            </td>
            <td>
                <%=Html.CheckBoxFor(...) %>
            </td>
        </tr>
        <%
}%>
    </table>
</code>```

I'm not sure how to handle the CheckBoxFor. I will also need to query these checkboxes when the Submit is clicked....

答:
The anwer to the displaying of the Checkboxes was to simply use this:</p>

```<code><%=Html.CheckBoxFor(x=>cat.Selected) %>
</code>```

Title: ASP.Net MVC List of Checkboxes

Body:
I am passing a model to a view, which containt a List of items. A DefaultCategories has an id (int), a description (string), and a selected boolean property.

I need to list these items, with a checkbox, and check the ones where the selected property is true.

So, I was trying this:

        Assigned Categories

        <%foreach (var cat in Model.DefaultCategories)
{%>

                <%=cat.Category %>

                <%=Html.CheckBoxFor(...) %>

        <%
}%>

I'm not sure how to handle the CheckBoxFor. I will also need to query these checkboxes when the Submit is clicked....

Body:
The anwer to the displaying of the Checkboxes was to simply use this:

<%=Html.CheckBoxFor(x=>cat.Selected) %>


问:
MongoDB connection error while deploying on ZEIT
i am new at React and i'm trying to deploy on zeit. Deploy is successful but on zeit it gives error like

/usr/src/app/bundle/programs/server/node_modules/fibers/future.js:280
                          throw(ex);
                          ^

```<code>Error: query parameter ssl is an incomplete value pair
    at module.exports (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/url_parser.js:47:15)
    at connect (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:401:16)
    at Function.MongoClient.connect (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:225:3)
    at new MongoConnection (packages/mongo/mongo_driver.js:169:11)
    at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
    at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
    at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
    at new Mongo.Collection (packages/mongo/collection.js:99:40)
    at AccountsServer.AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
    at new AccountsServer (packages/accounts-base/accounts_server.js:18:5)
</code>```

if anyone also get same error then please help.

答:
The error is from mongodb/lib/url_parser.js which means there's probably a problem with your MONGO_URL, perhaps around the SSL part.

https://docs.meteor.com/environment-variables.html#MONGO-URL

Body:
i am new at React and i'm trying to deploy on zeit. Deploy is successful but on zeit it gives error like

/usr/src/app/bundle/programs/server/node_modules/fibers/future.js:280
                          throw(ex);
                          ^

Error: query parameter ssl is an incomplete value pair
    at module.exports (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/url_parser.js:47:15)
    at connect (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:401:16)
    at Function.MongoClient.connect (/usr/src/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:225:3)
    at new MongoConnection (packages/mongo/mongo_driver.js:169:11)
    at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
    at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
    at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
    at new Mongo.Collection (packages/mongo/collection.js:99:40)
    at AccountsServer.AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
    at new AccountsServer (packages/accounts-base/accounts_server.js:18:5)

if anyone also get same error then please help.


问:
Regex - Don't match a group if it starts with a string in javascript
I'm struggling with some regex, in javascript which doesn't have a typical lookbehind option, to only match a group if it's not preceded with a string:

```<code>(^|)(www\.[\S]+?(?= |[,;:!?]|\.( )|$))
</code>```

so in the following

```<code>hello http:/www.mytestwebsite.com is awesome
</code>```

I'm trying to detect if the www.mytestwebsite.com is preceeded by

```<code>/
</code>```

and if it is I don't want to match, otherwise match away. I tried using a look ahead but it looked to be conflicting with the look ahead I already had.

I've been playing around with placing (?!&#x2f) in different areas with no success.

```<code>(^|)((?!&#x2f)www\.[\S]+?(?= |[,;:!?]|\.( )|$))
</code>```

A look ahead to not match if the match is preceded

答:
Another option (and I've done zero performance testing) would be to use string.replace() with a regex and a callback as the second parameter.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Then, inside of the replace function, prepend/append the illegal/characters you don't want to match to the matched string, using the offset parameter passed to the callback (see above docs) you can determine each match, and it's position and make a determination whether to replace the text or not.

Body:
I'm struggling with some regex, in javascript which doesn't have a typical lookbehind option, to only match a group if it's not preceded with a string:

(^|)(www\.[\S]+?(?= |[,;:!?]|\.( )|$))

so in the following

hello http:/www.mytestwebsite.com is awesome

I'm trying to detect if the www.mytestwebsite.com is preceeded by

/

and if it is I don't want to match, otherwise match away. I tried using a look ahead but it looked to be conflicting with the look ahead I already had.

I've been playing around with placing (?!&#x2f) in different areas with no success.

(^|)((?!&#x2f)www\.[\S]+?(?= |[,;:!?]|\.( )|$))

A look ahead to not match if the match is preceded


问:
How can I instal cx_Oracle package to Anaconda 3 to use with python 3.5
I need to connect to Oracle database in Python Anaconda3-2.5.0-Windows-x86_64. Installation of the cx_Oracle module by:

```<code>conda install -c https://conda.anaconda.org/anaconda cx_oracle
</code>```

fails with following output (trimmed):

```<code>Hint: the following packages conflict with each other:
  - cx_oracle
  - python 3.5*
</code>```

So I tried to install package for Python 3.5 by 'cx_Oracle-5.2.1-11g.win-amd64-py3.5.exe' from https://pypi.python.org/pypi/cx_Oracle/ Which seems to be working (somehow). Even 'conda list' command prints line:

```<code>cx-oracle                 5.2.1                     <pip>
</code>```

But when I enter import cx_Oracle; in Python then

```<code>ImportError: DLL load failed: Uvedený modul nebyl nalezen.
</code>```

appears. Rough translation of last localized part is 'Modul not found.'

How can I install the cx_Oracle module? Or is there any other way to connect to Oracle database?

答:
In the Anaconda navigator, select 'Environments', then on the right, change the filter to 'All'. Now you can query for 'cx_oracle', select it and at the bottom, select 'Apply'. Once completed, you should be able to</p>

```<code>import oracle
</code>```

Body:
I need to connect to Oracle database in Python Anaconda3-2.5.0-Windows-x86_64. Installation of the cx_Oracle module by:

conda install -c https://conda.anaconda.org/anaconda cx_oracle

fails with following output (trimmed):

Hint: the following packages conflict with each other:
  - cx_oracle
  - python 3.5*

So I tried to install package for Python 3.5 by 'cx_Oracle-5.2.1-11g.win-amd64-py3.5.exe' from https://pypi.python.org/pypi/cx_Oracle/ Which seems to be working (somehow). Even 'conda list' command prints line:

cx-oracle                 5.2.1                     <pip>

But when I enter import cx_Oracle; in Python then

ImportError: DLL load failed: Uvedený modul nebyl nalezen.

appears. Rough translation of last localized part is 'Modul not found.'

How can I install the cx_Oracle module? Or is there any other way to connect to Oracle database?

Body:
In the Anaconda navigator, select 'Environments', then on the right, change the filter to 'All'. Now you can query for 'cx_oracle', select it and at the bottom, select 'Apply'. Once completed, you should be able to

import oracle


问:
Export Appointment to outlook using Angularjs
I am using addeventatc. As per research i have to use addeventatc.refresh(); after page page loaded because i am using data from api call.It works if i put button on my screen. But not working with loading.

Here website https://www.addevent.com/add-to-calendar-button .

```<code>    <tr ng-repeat="y in x.LEAVE_DAYS | orderBy:'LEAVE_DATE'">
                                                <td>
    <span ng-show="test" title="Add to Calendar" class="addeventatc">
    <br />
    <span class="start">{{y.LEAVE_START | date:'M/d/yy h:mm a'}}</span>
    <span class="end">{{y.LEAVE_END | date:'M/d/yy h:mm a'}}</span>
    <span class="timezone">US/Arizona</span>
    <span class="title">Time Approved for {{x.REQ_TYPE}}</span>
    <span class="description">Approved Hours :  {{y.HOURS}}</span>
     </span>
     </td>
</code>```

I tried as below its work. But i do want to fire this function after my table load on screen.

```<code>button type="button" class="btn btn-primary" ng-click="testing(); test=true">&nbsp Exports data</button>
</code>```

controller

```<code>  $scope.testing = function () {
    addeventatc.refresh();
}
</code>```

答:
Try adding a timeout function</p>

```<code>setTimeout(function(){
   addeventatc.refresh();
}, 200);
</code>```

Body:
I am using addeventatc. As per research i have to use addeventatc.refresh(); after page page loaded because i am using data from api call.It works if i put button on my screen. But not working with loading.

Here website https://www.addevent.com/add-to-calendar-button .

    {{y.LEAVE_START | date:'M/d/yy h:mm a'}}
    {{y.LEAVE_END | date:'M/d/yy h:mm a'}}
    US/Arizona
    Time Approved for {{x.REQ_TYPE}}
    Approved Hours :  {{y.HOURS}}

I tried as below its work. But i do want to fire this function after my table load on screen.

button type="button" class="btn btn-primary" ng-click="testing(); test=true">&nbsp Exports data</button>

controller

  $scope.testing = function () {
    addeventatc.refresh();
}

Body:
Try adding a timeout function

setTimeout(function(){
   addeventatc.refresh();
}, 200);


问:
Wildcard while comparing strings on JavaScript
I need to compare 2 Strings, is there any wildcard character?

In case that there is none wildcard, how can i do this? The strings to compare are concatenations of substrings like this HHH-H-HHH separated by ','.

Example:

```<code>var str1 = "HHH-H-HHH,OOO-O-OOO"

var str2 = "HHH-$-HHH,OOO-O-OOO"

var str3 = "HHH-H-HHH,OOO-$-OOO"

var str4 = "HHH-H-HHH,OOO-U-OOO"

str1.equals(str2) // SHOULD BE TRUE

str1.equals(str3) // SHOULD BE TRUE

str1.equals(str4) // SHOULD BE FALSE
</code>```

答:
Use regex:

var str1 = "HHH-H-HHH,OOO-O-OOO"
var str2 = "HHH-H-HHH,OOO-U-OOO"

var rgx1 = /HHH-.*-HHH,OOO-O-OOO/
var rgx2 = /HHH-H-HHH,OOO-.*-OOO/

console.log(rgx1.test(str1)) // SHOULD BE TRUE
console.log(rgx2.test(str1)) // SHOULD BE TRUE
console.log(str1 === str2) // SHOULD BE FALSE```

The .* operator in regex matches anything, so that's your wildcard. Note that this way you have to make a distinction between values and patterns. That is, there are the strings you want to check, and the patterns you want to check them against (represented here by the regexes).

If you're comparing against a pattern, use a regex (first two examples). If you're comparing two values, just do it directly with the === operator (last example).

Body:
I need to compare 2 Strings, is there any wildcard character?

In case that there is none wildcard, how can i do this? The strings to compare are concatenations of substrings like this HHH-H-HHH separated by ','.

Example:

var str1 = "HHH-H-HHH,OOO-O-OOO"

var str2 = "HHH-$-HHH,OOO-O-OOO"

var str3 = "HHH-H-HHH,OOO-$-OOO"

var str4 = "HHH-H-HHH,OOO-U-OOO"

str1.equals(str2) // SHOULD BE TRUE

str1.equals(str3) // SHOULD BE TRUE

str1.equals(str4) // SHOULD BE FALSE

Body:
Use regex:

var str1 = "HHH-H-HHH,OOO-O-OOO"
var str2 = "HHH-H-HHH,OOO-U-OOO"

var rgx1 = /HHH-.*-HHH,OOO-O-OOO/
var rgx2 = /HHH-H-HHH,OOO-.*-OOO/

console.log(rgx1.test(str1)) // SHOULD BE TRUE
console.log(rgx2.test(str1)) // SHOULD BE TRUE
console.log(str1 === str2) // SHOULD BE FALSE

The .* operator in regex matches anything, so that's your wildcard. Note that this way you have to make a distinction between values and patterns. That is, there are the strings you want to check, and the patterns you want to check them against (represented here by the regexes).

If you're comparing against a pattern, use a regex (first two examples). If you're comparing two values, just do it directly with the === operator (last example).