问:
Single page website navigation selected states
New to SO! Please suggest a better way to phrase this question :)

I have a single page, vertical scrolling website with a fixed navigation bar located in the footer. I am using local.scroll and anchors to link the navigation to divs on the page.

I would like the user to be able to click on one link and have it change to a selected state. I'm just not sure how to style/code the links for a single page (instead of using class="select" for each active link as in multiple page sites.)

This site has an example of what I'd like to accomplish:
http://www.kristaganelon.com/#portfolio-section

答:
The example you referenced is using Javascript (in the form of the popular library JQuery) to create the selected state on the navigation as well as scroll the page.

JQuery

This library is very popular for creating the kind of event handlers you are looking for, as it easily binds events using simple CSS selectors familiar to anyone who has styled a page with CSS.  The conventions of IDs, classes and attributes are used to find elements and bind events or change their states.

The JQuery site has plenty of helpful tutorials, but a simple click event looks something like this:

```<code>    $(document).ready(function(){
      $('.button').click(function(){
        alert('You clicked me!');
    });
});
</code>```

You could utilize JQuery's .addClass to make clicking the element give it certain visual state:

```<code>$(document).ready(function(){
      $('.button').click(function(){
        $(this).addClass('clicked');
    });
});
</code>```

I suggest you look over the libraries documentation and learn how to first include it on your page, and then look over some basic event binding, toggling (since you'll need this to remove the active state), etc.  Learning these things will help you create interactive elements much easier.

Body:
The example you referenced is using Javascript (in the form of the popular library JQuery) to create the selected state on the navigation as well as scroll the page.

JQuery

This library is very popular for creating the kind of event handlers you are looking for, as it easily binds events using simple CSS selectors familiar to anyone who has styled a page with CSS.  The conventions of IDs, classes and attributes are used to find elements and bind events or change their states.

The JQuery site has plenty of helpful tutorials, but a simple click event looks something like this:

    $(document).ready(function(){
      $('.button').click(function(){
        alert('You clicked me!');
    });
});

You could utilize JQuery's .addClass to make clicking the element give it certain visual state:

$(document).ready(function(){
      $('.button').click(function(){
        $(this).addClass('clicked');
    });
});

I suggest you look over the libraries documentation and learn how to first include it on your page, and then look over some basic event binding, toggling (since you'll need this to remove the active state), etc.  Learning these things will help you create interactive elements much easier.


来源: stackexchange

问:
3 images centered in a row
I am trying to have three images centered in a row and then centered on the page. I've got them all in a row but I cannot get them centered. Any suggestions on getting my group to the middle? I tried 0 auto on the contain class and on the social class. so close!!

My HTML: first thing is div class=contain to wrap the whole thing, but for some reason if I try to include the class contain in HTML it disppears on Stack Overflow so excuse that.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

答:
Maybe you can edit the css file, remove the float:left; :

.contain {
     max-width:960px;
     text-align:center;
  }

 .social {
 position:relative;
 display: inline-block;
 padding: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div align="center">
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
</div>
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png"
alt="" width="75" height="75" />
</div>
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: 3 images centered in a row

Body:
Maybe you can edit the css file, remove the float:left; :

.contain {
     max-width:960px;
     text-align:center;
  }

 .social {
 position:relative;
 display: inline-block;
 padding: 10px;
 }

<div align="center">
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
</div>
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png"
alt="" width="75" height="75" />
</div>
<div align="center;" class="social">
<img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
</div>
</div>


问:
How to get real shape of None (dynamic input shape) in TensorFlow?
I have a placeholder which shape is [None, dimension], "None" means batch size. I want to get the real shape of "None".

I try two methods when I build model:

First, x.get_shape() and get shape as [Dimension(None), Dimension(128)]

Second, x.shape and get shape as [Dimension(None), Dimension(128)]

And what I want is the real shape, for example, when the batch size is 100 in this round, I would like to get [Dimension(100), Dimension(128)].

How do I get the dynamic input shape?

答:
I believe tf.shape is what you are looking for.

tf.shape(x) can get the shape while session is running.

The full example is below:

```<code>import tensorflow as tf
a = tf.ones([3,4])
b = tf.shape(a)
sess=tf.Session()
print(b.eval(session=sess))
</code>```

You can also use b to init new variables.

Body:
I believe tf.shape is what you are looking for.

tf.shape(x) can get the shape while session is running.

The full example is below:

import tensorflow as tf
a = tf.ones([3,4])
b = tf.shape(a)
sess=tf.Session()
print(b.eval(session=sess))

You can also use b to init new variables.


问:
How to get the Text of a Div Class and Place inside a Label?
I'm trying to get the "valor" that is inside the site div from Poloniex to put inside a Label every 1 second using Timer after load site completely.

My Completely Code:

https://pastebin.com/QrcuWnxf

Div:

```<code><div class="info">valor</div>
</code>```

I have found that on the page there are several "info" classes...

This code worked, but it brought another result than expected ...

```<code>    Dim theElementCollection As HtmlElementCollection
    theElementCollection = WebBrowser1.Document.GetElementsByTagName("Div")
    For Each curElement As HtmlElement In theElementCollection
        If curElement.OuterHtml.Contains("info") Then
            Variable1 = (curElement.GetAttribute("InnerText"))
        End If
    Next

Label1.Text = Variable1
</code>```

The result was the value of this Div that also has the "info" class.

```<code><div class="msg"><div class="info">OMG/BTC and OMG/ETH  OmiseGO markets added</div>
</code>```

答:
Change the second try:

```<code>For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("div")
  If Element.GetAttribute("className") = "lastPrice" Then
   For Each Element1 As HtmlElement In Element.GetElementsByTagName("div")
        If Element1.GetAttribute("className") = "info" Then
            Dim Variable1 as String = Element1.InnerText
        End If
    Next
  End If
Next
</code>```

Yes, you have to use className for class attribute.

This code is verified against the following HTML: This also have more than 1 info class.

```<code><html>
 <body>
  <div class="firstPrice">
   <div class="name">First Price</div>
   <div class="info">11650.00</div>
  </div>
  <div class="lastPrice">
   <div class="name">Last Price</div>
   <div class="info">11650.00</div>
  </div>
 </body>
</html>
</code>```

Body:
I'm trying to get the "valor" that is inside the site div from Poloniex to put inside a Label every 1 second using Timer after load site completely.

My Completely Code:

https://pastebin.com/QrcuWnxf

Div:

valor

I have found that on the page there are several "info" classes...

This code worked, but it brought another result than expected ...

    Dim theElementCollection As HtmlElementCollection
    theElementCollection = WebBrowser1.Document.GetElementsByTagName("Div")
    For Each curElement As HtmlElement In theElementCollection
        If curElement.OuterHtml.Contains("info") Then
            Variable1 = (curElement.GetAttribute("InnerText"))
        End If
    Next

Label1.Text = Variable1

The result was the value of this Div that also has the "info" class.

OMG/BTC and OMG/ETH  OmiseGO markets added

Body:
Change the second try:

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("div")
  If Element.GetAttribute("className") = "lastPrice" Then
   For Each Element1 As HtmlElement In Element.GetElementsByTagName("div")
        If Element1.GetAttribute("className") = "info" Then
            Dim Variable1 as String = Element1.InnerText
        End If
    Next
  End If
Next

Yes, you have to use className for class attribute.

This code is verified against the following HTML: This also have more than 1 info class.

<html>
 <body>
  <div class="firstPrice">
   <div class="name">First Price</div>
   <div class="info">11650.00</div>
  </div>
  <div class="lastPrice">
   <div class="name">Last Price</div>
   <div class="info">11650.00</div>
  </div>
 </body>
</html>


问:
Flask-SQLAlchemy won't update or delete a row
I want to either update a row in the database, if it exists, or create it if it doesn't.

I have a class that first sets the instance variable user:

```<code>self.user = models.User.query.filter_by(entity=self.entityUrl).first()
# can be None if not found
</code>```

Then, later on in another class method I do this:

```<code>if self.user is not None:
    self.user.foo = bar  # etc. Change the attributes of self.user
else:
    self.user = models.User(bar, ... )  # create a new model
    db.session.add(self.user)
db.session.commit()
</code>```

Problem is, the corresponding row in the database doesn't get updated. I've also tried this approach:

```<code>if self.user is not None:
    self.user.foo = bar
else:
    self.user = models.User(bar, ... )
db.session.add(self.user)  # add it to the session either way
db.session.commit()
</code>```

Here, the db.session.add() call fails with sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7f4918172890>' is already attached to session '1' (this is '2')

And the first thing I tried was to delete the existing model in all cases, then create a new one, i.e.:

```<code>if self.user is not None:
    db.session.delete(self.user)
self.user = models.User(bar, ... )
db.session.add(self.user)
db.session.commit()
</code>```

In this case the db.session.delete() call fails with the same already attached to session '1' message as above.

Why is the object attached to a different session and not the same one? How do I do this correctly?

答:
Make sure the foo attribute in your class existes. Next, maybe there is something wrong in the way you use it. Because I see you use "self.user....". Try the simplest thing first. Then step by step.

The following code is wrong:

```<code>if self.user is not None:
    self.user.foo = bar
else:
    self.user = models.User(bar, ... )
db.session.add(self.user)  # add it to the session either way
db.session.commit()
</code>```

NO need to db.session.add, if you want to update the record.

Body:
I want to either update a row in the database, if it exists, or create it if it doesn't.

I have a class that first sets the instance variable user:

self.user = models.User.query.filter_by(entity=self.entityUrl).first()
# can be None if not found

Then, later on in another class method I do this:

if self.user is not None:
    self.user.foo = bar  # etc. Change the attributes of self.user
else:
    self.user = models.User(bar, ... )  # create a new model
    db.session.add(self.user)
db.session.commit()

Problem is, the corresponding row in the database doesn't get updated. I've also tried this approach:

if self.user is not None:
    self.user.foo = bar
else:
    self.user = models.User(bar, ... )
db.session.add(self.user)  # add it to the session either way
db.session.commit()

Here, the db.session.add() call fails with sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7f4918172890>' is already attached to session '1' (this is '2')

And the first thing I tried was to delete the existing model in all cases, then create a new one, i.e.:

if self.user is not None:
    db.session.delete(self.user)
self.user = models.User(bar, ... )
db.session.add(self.user)
db.session.commit()

In this case the db.session.delete() call fails with the same already attached to session '1' message as above.

Why is the object attached to a different session and not the same one? How do I do this correctly?

Body:
Make sure the foo attribute in your class existes. Next, maybe there is something wrong in the way you use it. Because I see you use "self.user....". Try the simplest thing first. Then step by step.

The following code is wrong:

if self.user is not None:
    self.user.foo = bar
else:
    self.user = models.User(bar, ... )
db.session.add(self.user)  # add it to the session either way
db.session.commit()

NO need to db.session.add, if you want to update the record.


问:
Automatically terminate class while children still reference it
I have created a class where its children hold a necessary reference to their parent. This means, when the parent class goes out of scope in the routine which calls it, its terminate code is not called, as the children still hold a reference to it.

Is there a way of terminating the parent without having to manually terminate the children first too?

Current work around is to make the parent's terminate code (which contains code to terminate the children) public and to call it from the routine, but this is not ideal as then the parent is terminated twice (once manually, once when it leaves the caller sub's scope). But mainly I don't like having to call it manually

```<code>'Caller code
Sub runTest()
    Dim testClass As parentClass
    Set testClass = New parentClass
    Set testClass = Nothing
End Sub

'parentClass
Private childrenGroup As New Collection

Private Sub Class_Initialize()
    Dim childA As New childClass
    Dim childB As New childClass
    childA.Setup "childA", Me 'give name and parent reference to child class
    childB.Setup "childB", Me
    childrenGroup.Add childA 'add children to collection
    childrenGroup.Add childB
End Sub

Public Sub Class_Terminate()
    Set childrenGroup = Nothing
    Debug.Print "Parent terminated"
End Sub

'childClass
Private className As String
Private parent As classParent

Public Sub Setup(itemName As String, parentObj As classParent)
    Set parent = parentObj 'set the reference
    className = itemName
End Sub

Public Property Get Name() As String
    Name = className
End Property

Private Sub Class_Terminate()
    Debug.Print Name;" was terminated" 'only called when parent terminates child
End Sub
</code>```

Calling runTest() prints

```<code>childA was terminated
childB was terminated
Parent terminated
Parent terminated 'to get around this, you could just make another sub in the parent class
                  'to terminate its children
                  'but that still requires a manual call
</code>```

答:
Having reviewed your comments, I'm still not convinced you need to pass the parent into the child class. If your only reason for doing so is to create a kind of callback then you'd probably be better off passing an event delegate class to the child instead of the parent class and then simply handle the delegate's events in your parent class. As you've seen, your current structure is causing some object disposal issues and these can be avoided.

Simply create a class containing your child events. In this example I've called the class clsChildEvents:

```<code>Option Explicit

Public Event NameChange(obj As clsChild)

Public Sub NotifyNameChange(obj As clsChild)
    RaiseEvent NameChange(obj)
End Sub
</code>```

Now your code remains pretty much as is. The key difference is that you are passing the delegate instead of the parent to the child objects.

Parent class:

```<code>Option Explicit

Private WithEvents mChildEvents As clsChildEvents
Private mChildren As Collection

Public Sub SetUp()
    Dim child As clsChild

    Set child = New clsChild
    child.SetUp "ChildA", mChildEvents
    mChildren.Add child

    Set child = New clsChild
    child.SetUp "ChildB", mChildEvents
    mChildren.Add child

End Sub

Private Sub mChildEvents_NameChange(obj As clsChild)
    Debug.Print "New name for "; obj.Name
End Sub

Private Sub Class_Initialize()
    Set mChildEvents = New clsChildEvents
    Set mChildren = New Collection
End Sub

Private Sub Class_Terminate()
    Debug.Print "Parent terminated."
End Sub
</code>```

Child class:

```<code>Option Explicit

Private mClassName As String
Private mEvents As clsChildEvents

Public Sub SetUp(className As String, delegate As clsChildEvents)
    Set mEvents = delegate
    Me.Name = className
End Sub
Public Property Get Name() As String
    Name = mClassName
End Property

Public Property Let Name(RHS As String)
    mClassName = RHS
    mEvents.NotifyNameChange Me
End Property

Private Sub Class_Terminate()
    Debug.Print mClassName; " terminated."
End Sub
</code>```

And then your module code:

```<code>Option Explicit

Public Sub Test()
    Dim parent As clsParent

    Set parent = New clsParent
    parent.SetUp

    Set parent = Nothing
End Sub
</code>```

The immediate window output is as follows:

New name for ChildA

New name for ChildB

Parent terminated.

ChildA terminated.

ChildB terminated.

Body:
I have created a class where its children hold a necessary reference to their parent. This means, when the parent class goes out of scope in the routine which calls it, its terminate code is not called, as the children still hold a reference to it.

Is there a way of terminating the parent without having to manually terminate the children first too?

Current work around is to make the parent's terminate code (which contains code to terminate the children) public and to call it from the routine, but this is not ideal as then the parent is terminated twice (once manually, once when it leaves the caller sub's scope). But mainly I don't like having to call it manually

'Caller code
Sub runTest()
    Dim testClass As parentClass
    Set testClass = New parentClass
    Set testClass = Nothing
End Sub

'parentClass
Private childrenGroup As New Collection

Private Sub Class_Initialize()
    Dim childA As New childClass
    Dim childB As New childClass
    childA.Setup "childA", Me 'give name and parent reference to child class
    childB.Setup "childB", Me
    childrenGroup.Add childA 'add children to collection
    childrenGroup.Add childB
End Sub

Public Sub Class_Terminate()
    Set childrenGroup = Nothing
    Debug.Print "Parent terminated"
End Sub

'childClass
Private className As String
Private parent As classParent

Public Sub Setup(itemName As String, parentObj As classParent)
    Set parent = parentObj 'set the reference
    className = itemName
End Sub

Public Property Get Name() As String
    Name = className
End Property

Private Sub Class_Terminate()
    Debug.Print Name;" was terminated" 'only called when parent terminates child
End Sub

Calling runTest() prints

childA was terminated
childB was terminated
Parent terminated
Parent terminated 'to get around this, you could just make another sub in the parent class
                  'to terminate its children
                  'but that still requires a manual call

Body:
Having reviewed your comments, I'm still not convinced you need to pass the parent into the child class. If your only reason for doing so is to create a kind of callback then you'd probably be better off passing an event delegate class to the child instead of the parent class and then simply handle the delegate's events in your parent class. As you've seen, your current structure is causing some object disposal issues and these can be avoided.

Simply create a class containing your child events. In this example I've called the class clsChildEvents:

Option Explicit

Public Event NameChange(obj As clsChild)

Public Sub NotifyNameChange(obj As clsChild)
    RaiseEvent NameChange(obj)
End Sub

Now your code remains pretty much as is. The key difference is that you are passing the delegate instead of the parent to the child objects.

Parent class:

Option Explicit

Private WithEvents mChildEvents As clsChildEvents
Private mChildren As Collection

Public Sub SetUp()
    Dim child As clsChild

    Set child = New clsChild
    child.SetUp "ChildA", mChildEvents
    mChildren.Add child

    Set child = New clsChild
    child.SetUp "ChildB", mChildEvents
    mChildren.Add child

End Sub

Private Sub mChildEvents_NameChange(obj As clsChild)
    Debug.Print "New name for "; obj.Name
End Sub

Private Sub Class_Initialize()
    Set mChildEvents = New clsChildEvents
    Set mChildren = New Collection
End Sub

Private Sub Class_Terminate()
    Debug.Print "Parent terminated."
End Sub

Child class:

Option Explicit

Private mClassName As String
Private mEvents As clsChildEvents

Public Sub SetUp(className As String, delegate As clsChildEvents)
    Set mEvents = delegate
    Me.Name = className
End Sub
Public Property Get Name() As String
    Name = mClassName
End Property

Public Property Let Name(RHS As String)
    mClassName = RHS
    mEvents.NotifyNameChange Me
End Property

Private Sub Class_Terminate()
    Debug.Print mClassName; " terminated."
End Sub

And then your module code:

Option Explicit

Public Sub Test()
    Dim parent As clsParent

    Set parent = New clsParent
    parent.SetUp

    Set parent = Nothing
End Sub

The immediate window output is as follows:

New name for ChildA

New name for ChildB

Parent terminated.

ChildA terminated.

ChildB terminated.


问:
How to make xargs append trailing arguments with -n?
xargs is good at inserting initial arguments:

```<code>seq 0 10 | xargs -n 3 echo foo
</code>```

produces this output:

```<code>foo 0 1 2
foo 3 4 5
foo 6 7 8
foo 9 10
</code>```

What about when I also want trailing arguments?
That is, what command:

```<code>seq 0 10 | xargs -n 3 <WHAT GOES HERE?>
</code>```

will produce the following desired output:

```<code>foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar
</code>```

I tried the following:

```<code>seq 0 10 | xargs -n 3 -I {} echo foo {} bar
</code>```

which is almost right, except that it apparently forces 1 item per command line, which isn't what I want:

```<code>foo 0 bar
foo 1 bar
foo 2 bar
foo 3 bar
foo 4 bar
foo 5 bar
foo 6 bar
foo 7 bar
foo 8 bar
foo 9 bar
foo 10 bar
</code>```

答:
After figuring this out with a head-start from @netniV's answer,
I now see that the man page actually contains an example
showing how to do it:

```<code>xargs sh -c 'emacs "$@" < /dev/tty' emacs
</code>```

Launches  the  minimum  number of copies of Emacs needed, one after the
  other, to edit the files listed on xargs' standard input.  This example
  achieves the same effect as BSD's -o option, but in a more flexible and portable way.

And the wikipedia page shows a similar technique, with an explanation of the dummy arg at the end:

Another way to achieve a similar effect is to use a shell as the launched command, and deal with the complexity in that shell, for
  example:

```<code>$ mkdir ~/backups
$ find /path -type f -name '*~' -print0 | xargs -0 bash -c 'for filename; do cp -a "$filename" ~/backups; done' bash
</code>```

The word bash at the end of the line is interpreted by bash -c as special parameter $0. If the word bash weren't present, the name of
  the first matched file would be assigned to $0 and the file wouldn't
  be copied to ~/backups. Any word can be used instead of bash, but
  since $0 usually expands to the name of the shell or shell script
  being executed, bash is a good choice.

So, here's how to do it:

```<code>seq 0 10 | xargs -n 3 sh -c 'echo foo "$@" bar' some_dummy_string
</code>```

The output is as desired:

```<code>foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar
</code>```

ContentLicense: CC BY-SA 4.0

Body:
xargs is good at inserting initial arguments:

seq 0 10 | xargs -n 3 echo foo

produces this output:

foo 0 1 2
foo 3 4 5
foo 6 7 8
foo 9 10

What about when I also want trailing arguments?
That is, what command:

seq 0 10 | xargs -n 3 <WHAT GOES HERE?>

will produce the following desired output:

foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar

I tried the following:

seq 0 10 | xargs -n 3 -I {} echo foo {} bar

which is almost right, except that it apparently forces 1 item per command line, which isn't what I want:

foo 0 bar
foo 1 bar
foo 2 bar
foo 3 bar
foo 4 bar
foo 5 bar
foo 6 bar
foo 7 bar
foo 8 bar
foo 9 bar
foo 10 bar

Body:
After figuring this out with a head-start from @netniV's answer,
I now see that the man page actually contains an example
showing how to do it:

xargs sh -c 'emacs "$@" < /dev/tty' emacs

Launches  the  minimum  number of copies of Emacs needed, one after the
  other, to edit the files listed on xargs' standard input.  This example
  achieves the same effect as BSD's -o option, but in a more flexible and portable way.

And the wikipedia page shows a similar technique, with an explanation of the dummy arg at the end:

Another way to achieve a similar effect is to use a shell as the launched command, and deal with the complexity in that shell, for
  example:

$ mkdir ~/backups
$ find /path -type f -name '*~' -print0 | xargs -0 bash -c 'for filename; do cp -a "$filename" ~/backups; done' bash

The word bash at the end of the line is interpreted by bash -c as special parameter $0. If the word bash weren't present, the name of
  the first matched file would be assigned to $0 and the file wouldn't
  be copied to ~/backups. Any word can be used instead of bash, but
  since $0 usually expands to the name of the shell or shell script
  being executed, bash is a good choice.

So, here's how to do it:

seq 0 10 | xargs -n 3 sh -c 'echo foo "$@" bar' some_dummy_string

The output is as desired:

foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar


答:
Using flex is a great solution, but here's a solution that uses what you already have. By removing float: left from your existing code we can get the desired result.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  display: inline-block;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

Title: 3 images centered in a row

Body:
I am trying to have three images centered in a row and then centered on the page. I've got them all in a row but I cannot get them centered. Any suggestions on getting my group to the middle? I tried 0 auto on the contain class and on the social class. so close!!

My HTML: first thing is div class=contain to wrap the whole thing, but for some reason if I try to include the class contain in HTML it disppears on Stack Overflow so excuse that.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}

Body:
Using flex is a great solution, but here's a solution that uses what you already have. By removing float: left from your existing code we can get the desired result.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  display: inline-block;
  padding: 10px;
}

<div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div>


问:
Difference between normal for loop and for...in?
I'm trying to write a function to fulfil the following requirements:

Given an object and a key, "getElementsThatEqual10AtProperty" returns an array containing all the elements of the array located at the given key that are equal to ten.

Notes:

If the array is empty, it should return an empty array.

If the array contains no elements are equal to 10, it should return
an empty array.

If the property at the given key is not an array, it should return an
empty array.

If there is no property at the key, it should return an empty array.

Example:

```<code>var obj = {
  key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> [10, 10]
</code>```

Approach #1 (fails the final point *If there is no property at the key, it should return an empty array.):

```<code>function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (var i = 0; i < obj[key].length; i++) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
 return output;
}
</code>```

Approach #2 passes all:

```<code>function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (let i in obj[key]) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
  return output;
}
</code>```

From my understanding, both loops and the subsequent conditional push has the same logic. Why does one work over the other?

答:
You're making this more complicated than it needs to be. I would just do this:</p>

```<code>function getSameVals(yourArray, val){
  var a = [];
  for(var i=0,l=yourArray.length; i<l; i++){
    if(yourArray[i] === val){
      a.push(val);
    }
  }
  return a;
}
var ten = getSameVals(obj.key, 10);
console.log(ten);
</code>```

Body:
I'm trying to write a function to fulfil the following requirements:

Given an object and a key, "getElementsThatEqual10AtProperty" returns an array containing all the elements of the array located at the given key that are equal to ten.

Notes:

If the array is empty, it should return an empty array.

If the array contains no elements are equal to 10, it should return
an empty array.

If the property at the given key is not an array, it should return an
empty array.

If there is no property at the key, it should return an empty array.

Example:

var obj = {
  key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> [10, 10]

Approach #1 (fails the final point *If there is no property at the key, it should return an empty array.):

function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (var i = 0; i < obj[key].length; i++) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
 return output;
}

Approach #2 passes all:

function getElementsThatEqual10AtProperty(obj, key) {

  var output = [];
  for (let i in obj[key]) {
    if (obj[key][i] === 10) {
      output.push(obj[key][i]);
    }
  }
  return output;
}

From my understanding, both loops and the subsequent conditional push has the same logic. Why does one work over the other?

Body:
You're making this more complicated than it needs to be. I would just do this:

function getSameVals(yourArray, val){
  var a = [];
  for(var i=0,l=yourArray.length; i<l; i++){
    if(yourArray[i] === val){
      a.push(val);
    }
  }
  return a;
}
var ten = getSameVals(obj.key, 10);
console.log(ten);


问:
Can this class be changed into a React stateless function?
I am trying to change a react class into a stateless function but encounter some errors. Can you please help? The class is rendering a list in table format.

I first tried:

```<code>function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        );
                 }
             </tbody>
         </Table>
    );
}
</code>```

But got error:

```<code>JSX value should be either an expression or a quoted JSX text (345:39)

  343 |                         <div>Is Loading...</div> :
  344 |                         props.leases.map(lease =>
> 345 |                             <Lease key=lease._links.self.href
      |                                        ^
  346 |                                    lease=lease
  347 |                                    attributes=props.attributes
  348 |                                    handleDelete=props.handleDelete
</code>```

Then I tried to place brackets around leases like this:

```<code>function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        props.leases.map(lease =>
                            <Lease key={lease._links.self.href}
                                   lease={lease}
                                   attributes={props.attributes}
                                   handleDelete={props.handleDelete}
                                   handleUpdate={props.handleUpdate}/>
                        );
                 }
             </tbody>
         </Table>
    );
}
</code>```

But got error:

```<code>Unexpected token, expected } (350:25)

  348 |                                    handleDelete={props.handleDelete}
  349 |                                    handleUpdate={props.handleUpdate}/>
> 350 |                         );
      |                          ^
  351 |                  }
  352 |              </tbody>
  353 |          </Table>
</code>```

Update 1: Remove ; from );

```<code>function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                         props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        )
                 }
             </tbody>
         </Table>
    );
}
</code>```

Still failing with same error:

```<code>JSX value should be either an expression or a quoted JSX text (345:39)

  343 |                         <div>Is Loading...</div> :
  344 |                          props.leases.map(lease =>
> 345 |                             <Lease key=lease._links.self.href
      |                                        ^
  346 |                                    lease=lease
  347 |                                    attributes=props.attributes
  348 |                                    handleDelete=props.handleDelete
</code>```

答:
You forgot some curly braces line 345:</p>

```<code>function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        {props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        )}
                 }
             </tbody>
         </Table>
    );
}
</code>```

Body:
I am trying to change a react class into a stateless function but encounter some errors. Can you please help? The class is rendering a list in table format.

I first tried:

function LeaseList(props) {
    return (

                 {
                     props.isLoading ?

Is Loading...
 :
                        props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        );
                 }

    );
}

But got error:

JSX value should be either an expression or a quoted JSX text (345:39)

  343 |
Is Loading...
 :
  344 |                         props.leases.map(lease =>
> 345 |                             <Lease key=lease._links.self.href
      |                                        ^
  346 |                                    lease=lease
  347 |                                    attributes=props.attributes
  348 |                                    handleDelete=props.handleDelete

Then I tried to place brackets around leases like this:

function LeaseList(props) {
    return (

                 {
                     props.isLoading ?

Is Loading...
 :
                        props.leases.map(lease =>
                            <Lease key={lease._links.self.href}
                                   lease={lease}
                                   attributes={props.attributes}
                                   handleDelete={props.handleDelete}
                                   handleUpdate={props.handleUpdate}/>
                        );
                 }

    );
}

But got error:

Unexpected token, expected } (350:25)

  348 |                                    handleDelete={props.handleDelete}
  349 |                                    handleUpdate={props.handleUpdate}/>
> 350 |                         );
      |                          ^
  351 |                  }
  352 |

  353 |

Update 1: Remove ; from );

function LeaseList(props) {
    return (

                 {
                     props.isLoading ?

Is Loading...
 :
                         props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        )
                 }

    );
}

Still failing with same error:

JSX value should be either an expression or a quoted JSX text (345:39)

  343 |
Is Loading...
 :
  344 |                          props.leases.map(lease =>
> 345 |                             <Lease key=lease._links.self.href
      |                                        ^
  346 |                                    lease=lease
  347 |                                    attributes=props.attributes
  348 |                                    handleDelete=props.handleDelete

Body:
You forgot some curly braces line 345:

function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        {props.leases.map(lease =>
                            <Lease key=lease._links.self.href
                                   lease=lease
                                   attributes=props.attributes
                                   handleDelete=props.handleDelete
                                   handleUpdate=props.handleUpdate/>
                        )}
                 }
             </tbody>
         </Table>
    );
}


问:
Will XmlSuite.SetFileName(XXX) create a physical file?
Can we convert virtually created XML file into physically? For example, I'm generating testng.xml file programmatically and execute my test scripts along with that.

My expectation is, I need to create an XML file which is virtually created as I said above... I have used the below code but it’s not producing expected results.

```<code>    TestNG myTestNG = new TestNG();

     XmlSuite mySuite = new XmlSuite();
     mySuite.setName("MySuite");
     mySuite.setParallel(XmlSuite.ParallelMode.METHODS);

     XmlTest myTest = new XmlTest(mySuite);
     myTest.setName("MyTest");

    myTest.setParameters(testngParams);

     List<XmlClass> myClasses = new ArrayList<XmlClass> ();
     myClasses.add(new XmlClass("ThreadSample"));

     myTest.setXmlClasses(myClasses);

     List<XmlTest> myTests = new ArrayList<XmlTest>();
     myTests.add(myTest);

    //add the list of tests to your Suite.
     mySuite.setTests(myTests);

    //Add the suite to the list of suites.
     List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
     mySuites.add(mySuite);

     XmlSuite suite = getXmlSuite();
     mySuites.add(suite);

     myTestNG.setXmlSuites(mySuites);

     **suite.setFileName("user.dir" + System.getProperty("file.separator") + "myVirtual.xml");
     System.out.println("File generated successfully.");**

     myTestNG.setSuiteThreadPoolSize(3);
     myTestNG.setThreadCount(3);

     myTestNG.run();
</code>```

Can anyone help me to complete this?

答:
To create a physical testNG.xml file, you have to write the suites object at a given location. </p>

```<code>FileWriter writer;
try {
writer = new FileWriter(new File("myVirtual.xml"));
writer.write(mySuites.toXml());
writer.flush();
writer.close();
System.out.println(new File("myVirtual.xml").getAbsolutePath());
} catch (IOException e) {

e.printStackTrace();
}
</code>```

Body:
Can we convert virtually created XML file into physically? For example, I'm generating testng.xml file programmatically and execute my test scripts along with that.

My expectation is, I need to create an XML file which is virtually created as I said above... I have used the below code but it’s not producing expected results.

    TestNG myTestNG = new TestNG();

     XmlSuite mySuite = new XmlSuite();
     mySuite.setName("MySuite");
     mySuite.setParallel(XmlSuite.ParallelMode.METHODS);

     XmlTest myTest = new XmlTest(mySuite);
     myTest.setName("MyTest");

    myTest.setParameters(testngParams);

     List<XmlClass> myClasses = new ArrayList<XmlClass> ();
     myClasses.add(new XmlClass("ThreadSample"));

     myTest.setXmlClasses(myClasses);

     List<XmlTest> myTests = new ArrayList<XmlTest>();
     myTests.add(myTest);

    //add the list of tests to your Suite.
     mySuite.setTests(myTests);

    //Add the suite to the list of suites.
     List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
     mySuites.add(mySuite);

     XmlSuite suite = getXmlSuite();
     mySuites.add(suite);

     myTestNG.setXmlSuites(mySuites);

     **suite.setFileName("user.dir" + System.getProperty("file.separator") + "myVirtual.xml");
     System.out.println("File generated successfully.");**

     myTestNG.setSuiteThreadPoolSize(3);
     myTestNG.setThreadCount(3);

     myTestNG.run();

Can anyone help me to complete this?

Body:
To create a physical testNG.xml file, you have to write the suites object at a given location.

FileWriter writer;
try {
writer = new FileWriter(new File("myVirtual.xml"));
writer.write(mySuites.toXml());
writer.flush();
writer.close();
System.out.println(new File("myVirtual.xml").getAbsolutePath());
} catch (IOException e) {

e.printStackTrace();
}


问:
Async client response with cpp-netlib?
I am considering using cpp netlib for a new project. All of the examples show reading the body of the response in a blocking manner:

```<code>client::response response_ = client_.get(request_);
std::string body_ = body(response_);
</code>```

If I construct my client object with the async tag:

```<code>basic_client<http_async_8bit_udp_resolve_tags, 1, 1> client_();
</code>```

What affect does that have?

Is it possible to get the results of the body wrapper as a boost::shared_future<std::string>?

Do I just need to wrap the blocking call in it's own thread?

答:
Look at the current http client doc: http://cpp-netlib.org/0.12.0/reference/http_client.html

the http client is now always async by default

you have an option to provide a callback function or object in the get or post call:

```<code>struct body_handler {

    explicit body_handler(std::string & body)
    : body(body) {}

    BOOST_NETWORK_HTTP_BODY_CALLBACK(operator(), range, error) {
        // in here, range is the Boost.Range iterator_range, and error is
        // the Boost.System error code.
        if (!error)
            body.append(boost::begin(range), boost::end(range));
    }

    std::string & body;
};

// somewhere else
std::string some_string;
response_ = client_.get(request("http://cpp-netlib.github.com/"),
                    body_handler(some_string));
</code>```

The client::response object already incapsulates the future object:

The response object encapsulates futures which get filled in once the values are available.

Title: Async client response with cpp-netlib?

Body:
I am considering using cpp netlib for a new project. All of the examples show reading the body of the response in a blocking manner:

client::response response_ = client_.get(request_);
std::string body_ = body(response_);

If I construct my client object with the async tag:

basic_client<http_async_8bit_udp_resolve_tags, 1, 1> client_();

What affect does that have?

Is it possible to get the results of the body wrapper as a boost::shared_future<std::string>?

Do I just need to wrap the blocking call in it's own thread?

Body:
Look at the current http client doc: http://cpp-netlib.org/0.12.0/reference/http_client.html

the http client is now always async by default

you have an option to provide a callback function or object in the get or post call:

struct body_handler {

    explicit body_handler(std::string & body)
    : body(body) {}

    BOOST_NETWORK_HTTP_BODY_CALLBACK(operator(), range, error) {
        // in here, range is the Boost.Range iterator_range, and error is
        // the Boost.System error code.
        if (!error)
            body.append(boost::begin(range), boost::end(range));
    }

    std::string & body;
};

// somewhere else
std::string some_string;
response_ = client_.get(request("http://cpp-netlib.github.com/"),
                    body_handler(some_string));

The client::response object already incapsulates the future object:

The response object encapsulates futures which get filled in once the values are available.


问:
How to set MediaElement.Source from MediaStreamSource
I am using MediaElement tool because MediaPlayerElement tool is unavailable in my vs17 community. I  tying to build to this app but facing some error.

How can I solve this? I just copied the code from the link given above and replaced mediaplayer with mediaelement.

答:
The Source of MediaElement is Uri type, it Cannot implicitly convert type 'Windows.Media.Core.MediaSource' to 'System.Uri'. That's why you would get this error.

To solve it, you could change your code like the following:

```<code>mediaElement.SetMediaStreamSource(MediaSource.CreateFromMediaStreamSource(mediaStreamSource).MediaStreamSource);
</code>```

Body:
The Source of MediaElement is Uri type, it Cannot implicitly convert type 'Windows.Media.Core.MediaSource' to 'System.Uri'. That's why you would get this error.

To solve it, you could change your code like the following:

mediaElement.SetMediaStreamSource(MediaSource.CreateFromMediaStreamSource(mediaStreamSource).MediaStreamSource);


问:
How to find out date in which URL was shortened
may I know how do you find out when a particular URL was shortened using Bitly?</p>

答: Just add "+" to the end of the URL in your browser</p>


问:
Create ModelChoiceField with annotation
I need to make a selector with genders (male and female) with the respectives counts of each type.

For example, if I have 4 males and 8 females in my DB, I need a select tags with options

"Select gender"

"Male (4)"

"Female (8)"

In my Form class I have

```<code>gender = forms.ModelChoiceField(
        queryset=Gender.objects.all().annotate(counter=Count('user')),
        required=False,
        label="Gender"
    )
</code>```

And I don't know how to render this select element. If I use {{ form.gender }} I can't even display the options. I get Error binding parameter 0 - probably unsupported type. It could be an SQLite issue? I will use PostgreSQL as my DB anyway.

Any suggestions?

EDIT: I need something like this, with almost 10 form fields and a variable number of options in each case

答:
I would do it this way. I tried this and it works fine. Modify it for your needs and it should work fine as well. I am just modifying the widget for gender field.</p>

```<code>class testform(forms.ModelForm):
    class Meta:
        model = names
        fields = ['name', 'gender']

    male = 'male'+str(names.objects.filter(gender='m').count())
    female = 'female'+str(names.objects.filter(gender='f').count())
    choices = ((male, male),(female,female))
    gender = forms.CharField(widget=forms.Select(choices=choices))
</code>```

Title: Create ModelChoiceField with annotation

Body:
I need to make a selector with genders (male and female) with the respectives counts of each type.

For example, if I have 4 males and 8 females in my DB, I need a select tags with options

"Select gender"

"Male (4)"

"Female (8)"

In my Form class I have

gender = forms.ModelChoiceField(
        queryset=Gender.objects.all().annotate(counter=Count('user')),
        required=False,
        label="Gender"
    )

And I don't know how to render this select element. If I use {{ form.gender }} I can't even display the options. I get Error binding parameter 0 - probably unsupported type. It could be an SQLite issue? I will use PostgreSQL as my DB anyway.

Any suggestions?

EDIT: I need something like this, with almost 10 form fields and a variable number of options in each case

Body:
I would do it this way. I tried this and it works fine. Modify it for your needs and it should work fine as well. I am just modifying the widget for gender field.

class testform(forms.ModelForm):
    class Meta:
        model = names
        fields = ['name', 'gender']

    male = 'male'+str(names.objects.filter(gender='m').count())
    female = 'female'+str(names.objects.filter(gender='f').count())
    choices = ((male, male),(female,female))
    gender = forms.CharField(widget=forms.Select(choices=choices))


问:
How to use relative paths without including the context root name?
To working my static file (CSS, JS) I have to write absolute path like /AppName/templates/style/main.css. Is there any solution, that I could write relative path like style/main.css?

答:
You start tomcat from some directory - which is the $cwd for tomcat. You can specify any path relative to this $cwd.

suppose you have

```<code>home
- tomcat
 |_bin
- cssStore
 |_file.css
</code>```

And suppose you start tomcat from ~/tomcat, using the command "bin/startup.sh".

~/tomcat becomes the home directory ($cwd) for tomcat

You can access "../cssStore/file.css" from class files in your servlet now

Hope that helps, - M.S.

ContentLicense: CC BY-SA 2.5

Body:
You start tomcat from some directory - which is the $cwd for tomcat. You can specify any path relative to this $cwd.

suppose you have

home
- tomcat
 |_bin
- cssStore
 |_file.css

And suppose you start tomcat from ~/tomcat, using the command "bin/startup.sh".

~/tomcat becomes the home directory ($cwd) for tomcat

You can access "../cssStore/file.css" from class files in your servlet now

Hope that helps, - M.S.


答:
Try removing ; from line 345. There is no reason for this to be there. Also don't forget to use {} around the props.

```<code>function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        props.leases.map(lease =>
                            <Lease key={lease._links.self.href}
                                   lease={lease}
                                   attributes={props.attributes}
                                   handleDelete={props.handleDelete}
                                   handleUpdate={props.handleUpdate}/>
                        )
                 }
             </tbody>
         </Table>
    );
}
</code>```

Title: Can this class be changed into a React stateless function?

Body:
Try removing ; from line 345. There is no reason for this to be there. Also don't forget to use {} around the props.

function LeaseList(props) {
    return (
         <Table hover bordered striped responsive>
             <tbody>
                 {
                     props.isLoading ?
                        <div>Is Loading...</div> :
                        props.leases.map(lease =>
                            <Lease key={lease._links.self.href}
                                   lease={lease}
                                   attributes={props.attributes}
                                   handleDelete={props.handleDelete}
                                   handleUpdate={props.handleUpdate}/>
                        )
                 }
             </tbody>
         </Table>
    );
}


问:
How do I customize the "username already exists" message?
My forms.py has a custom user-creation class...

```<code>class RegisterForm(UserCreationForm):
 error_messages= {
  "password_mismatch": _("Passwords do not match."),
 }
</code>```

To clarify, I do not know which error_messages key corresponds to the one Django spits out when a user tries to sign up with a username that already exists. Which error message do I need to replace for when the user chooses a username that already exists?

答:
Maybe override the clean_username() method and Supply your own error_message:</p>

```<code>error_messages= {

"password_mismatch": _("Passwords do not match."),

"username_exists": _("Username already present`")}

def clean_username(self):
    username = self.cleaned_data.get("username")

    try:
        User._default_manager.get(username=username)
        #if the user exists, then let's raise an error message

        raise forms.ValidationError(
          self.error_messages['username_exists'],  #my error message

          code='username_exists',   #set the error message key

            )
    except User.DoesNotExist:
        return username # if user does not exist so we can continue the registration process
</code>```

Body:
My forms.py has a custom user-creation class...

class RegisterForm(UserCreationForm):
 error_messages= {
  "password_mismatch": _("Passwords do not match."),
 }

To clarify, I do not know which error_messages key corresponds to the one Django spits out when a user tries to sign up with a username that already exists. Which error message do I need to replace for when the user chooses a username that already exists?

Body:
Maybe override the clean_username() method and Supply your own error_message:

error_messages= {

"password_mismatch": _("Passwords do not match."),

"username_exists": _("Username already present`")}

def clean_username(self):
    username = self.cleaned_data.get("username")

    try:
        User._default_manager.get(username=username)
        #if the user exists, then let's raise an error message

        raise forms.ValidationError(
          self.error_messages['username_exists'],  #my error message

          code='username_exists',   #set the error message key

            )
    except User.DoesNotExist:
        return username # if user does not exist so we can continue the registration process


问:
How do I mass update an Eloquent model without a where condition?
I want to update all rows in a table with a new value for an Eloquent model. Laravel's documentation gives the following example for mass updates with Eloquent:

```<code>App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);
</code>```

But I don't need the where condition. Ideally, I'd be able to run something like this:

```<code>App\Flight::update(['delayed' => 1]);
</code>```

which omits the where clause. But this gives the error:

```<code>PHP Deprecated:  Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically on line 1
</code>```

How can I mass update all the rows in my table using Eloquent? I want to avoid using the DB::table('flights')->update(...) style if possible.

答:
This can be done using by running

```<code>App\Flight::query()->update(['delayed' => 1]);
</code>```

The query() method creates a new query builder instance, but without any initial clauses (like where conditions). Additional operations like update() can be chained after it.

Body:
I want to update all rows in a table with a new value for an Eloquent model. Laravel's documentation gives the following example for mass updates with Eloquent:

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

But I don't need the where condition. Ideally, I'd be able to run something like this:

App\Flight::update(['delayed' => 1]);

which omits the where clause. But this gives the error:

PHP Deprecated:  Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically on line 1

How can I mass update all the rows in my table using Eloquent? I want to avoid using the DB::table('flights')->update(...) style if possible.

Body:
This can be done using by running

App\Flight::query()->update(['delayed' => 1]);

The query() method creates a new query builder instance, but without any initial clauses (like where conditions). Additional operations like update() can be chained after it.


问:
Obtain column names via Perl DBI
In SQL Server Management Studio 2008, I can run

```<code>sp_columns MY_TABLE
</code>```

to get all the column names (under COLUMN_NAME). However, how can I obtain the same information using Perl DBI?

In particular, I tried

```<code>my $result = $dbh->selectall_hashref("sp_columns MY_TABLE", 'COLUMN_NAME');
</code>```

hoping that the column names would be the keys of the returned hash.

In fact, even if that's successful, that's not what I want as I need to preserve the order of columns in that table. So I tried

```<code>my $sth = $dbh->prepare("sp_columns $table");
$sth->execute();
while (my @row = $sth->fetchrow_array) {
    # process @row;
}
</code>```

But neither works. I got the error message of

```<code>DBD::Sybase::db selectall_hashref failed: Server message number=102 severity=15 state=1 line=1 server=XXXX text=Incorrect syntax near '.'
</code>```

I also referenced this post. Apparently the following query does NOT work in my Management Studio:

```<code>select * from information_schema.columns where table_name = MY_TABLE
</code>```

with the error message of

```<code>Msg 208, Level 16, State 1, Line 2
Invalid object name 'information_schema.columns'.
</code>```

Please help? Thx!

答: See the catalogue methods that DBI supports. In particular, I expect you want table_info.</p>

Title: Obtain column names via Perl DBI

Body:
In SQL Server Management Studio 2008, I can run

sp_columns MY_TABLE

to get all the column names (under COLUMN_NAME). However, how can I obtain the same information using Perl DBI?

In particular, I tried

my $result = $dbh->selectall_hashref("sp_columns MY_TABLE", 'COLUMN_NAME');

hoping that the column names would be the keys of the returned hash.

In fact, even if that's successful, that's not what I want as I need to preserve the order of columns in that table. So I tried

my $sth = $dbh->prepare("sp_columns $table");
$sth->execute();
while (my @row = $sth->fetchrow_array) {
    # process @row;
}

But neither works. I got the error message of

DBD::Sybase::db selectall_hashref failed: Server message number=102 severity=15 state=1 line=1 server=XXXX text=Incorrect syntax near '.'

I also referenced this post. Apparently the following query does NOT work in my Management Studio:

select * from information_schema.columns where table_name = MY_TABLE

with the error message of

Msg 208, Level 16, State 1, Line 2
Invalid object name 'information_schema.columns'.

Please help? Thx!


问:
Update OTB facets for anonymous user
Using Sitecore 8.2, Im having trouble consistently update email, and name fields for a contact. In MongoDB, I've seen the contacts collection updated with these fields previously with this code but I've just removed all rows from Contacts in  Mongo and executed the code below and there is no new entry in contacts</p>

```<code>Tracker.Current.Session.Identify(emailAddress);
var currentContact = Tracker.Current.Contact;

var personalFacet = currentContact .GetFacet<Sitecore.Analytics.Model.Entities.IContactPersonalInfo>("Personal");

personalFacet.FirstName = firstName;

personalFacet.Surname = surName;

XdbContactManager.SaveAndReleaseContact(currentContact);
</code>```

答:
Replacing

```<code>XdbContactManager.SaveAndReleaseContact(currentContact);
</code>```

with

```<code>XdbContactManager.FlushContactToXdb(currentContact);
</code>```

Seems to have fixed my issue

Title: Update OTB facets for anonymous user

Body:
Using Sitecore 8.2, Im having trouble consistently update email, and name fields for a contact. In MongoDB, I've seen the contacts collection updated with these fields previously with this code but I've just removed all rows from Contacts in  Mongo and executed the code below and there is no new entry in contacts

Tracker.Current.Session.Identify(emailAddress);
var currentContact = Tracker.Current.Contact;

var personalFacet = currentContact .GetFacet<Sitecore.Analytics.Model.Entities.IContactPersonalInfo>("Personal");

personalFacet.FirstName = firstName;

personalFacet.Surname = surName;

XdbContactManager.SaveAndReleaseContact(currentContact);

Body:
Replacing

XdbContactManager.SaveAndReleaseContact(currentContact);

with

XdbContactManager.FlushContactToXdb(currentContact);

Seems to have fixed my issue


问:
Why does Git report a random, non-existent directory or file as an untracked file?
After making a few changes within a repo, when I run a git status I get the following:

Untracked files:
   (use "git add ..." to include in what will be committed)

```<code>   "etting\357\200\233\357\200\233\357\200\233\357\200\233\357\200\272"
</code>```

This file does not exist. I'm not sure where the seemingly random numbers come from. Oddly, it's also surrounded in quotes. The status does also correctly show my modified files.

What could cause this? I've had it happen a few times before and had to perform a reset to return to a correct state. Is it possible the repo is corrupted in some way?

答:
You probably are committing a file you accidentally made called: "etting::::" or something similar. I had "c/357\200\272" because I accidentally made a file called 'c:' in that directory.

Just list what you have in that directory and you'll probably see the file that doesn't belong. Remove and you should be good.

Body:
After making a few changes within a repo, when I run a git status I get the following:

Untracked files:
   (use "git add ..." to include in what will be committed)

   "etting\357\200\233\357\200\233\357\200\233\357\200\233\357\200\272"

This file does not exist. I'm not sure where the seemingly random numbers come from. Oddly, it's also surrounded in quotes. The status does also correctly show my modified files.

What could cause this? I've had it happen a few times before and had to perform a reset to return to a correct state. Is it possible the repo is corrupted in some way?


问:
writing legacy views in Standard SQL format in Bigquery
I asked this question yesterday, I'm trying to write my legacy view in standard SQL.

My table is

```<code>FROM [myProject.Mydataset.ga_sessions_20171129]
</code>```

ga_sessions_20171129 is my table id and the last part of its name shows the last date that the table is updated, so the next table for the next day will be 20171130

We used this code to update the table every day

```<code>FROM `project.dataset.ga_sessions_*`
WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', CURRENT_DATE())
</code>```

But it didn't work and gave me this error:

Failed to save view. Views cannot be queried through prefix. Partial
  list of the matched views are:...

Later, we thought that because we have some tables like that  ga_sessions_S_20171129, it caused some confusion, then we tried this

```<code>FROM `project.dataset.ga_sessions_20*` where _TABLE_SUFFIX = FORMAT_DATE('%y%m%d', CURRENT_DATE())
</code>```

It still doesn't work. Does anyone have a clue about this?

答:
The ONLY explanation I see is that in same dataset you have view that has same prefix as other tables  - which is project.dataset.ga_sessions_* but wildcard table does not support views. The query returns an error if the wildcard table matches any views in the dataset

There are few more limitations for wildcard tables

Body:
I asked this question yesterday, I'm trying to write my legacy view in standard SQL.

My table is

FROM [myProject.Mydataset.ga_sessions_20171129]

ga_sessions_20171129 is my table id and the last part of its name shows the last date that the table is updated, so the next table for the next day will be 20171130

We used this code to update the table every day

FROM `project.dataset.ga_sessions_*`
WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', CURRENT_DATE())

But it didn't work and gave me this error:

Failed to save view. Views cannot be queried through prefix. Partial
  list of the matched views are:...

Later, we thought that because we have some tables like that  ga_sessions_S_20171129, it caused some confusion, then we tried this

FROM `project.dataset.ga_sessions_20*` where _TABLE_SUFFIX = FORMAT_DATE('%y%m%d', CURRENT_DATE())

It still doesn't work. Does anyone have a clue about this?


问:
Calculate a daily / weekly / monthly growth with python
I have a pretty complicated problem with absolutely no idea how to solve : I'm trying to calculate a daily/weekly/montlhy growth of some data.

The difficulty lies in the fact that I'm collecting data points randomly. So we can have data like that :

```<code>Date | orders

2017-01-12 |  1992
2017-01-13 |  2912
2017-02-10 |  3912
2017-02-11 |  4112
2017-02-12 |  4412
2017-02-16 |  5112
2017-03-01 |  8112
</code>```

I have HUGE quantity of data, so I don't think it would be possible to actually build this without creating a temporary table that would store the results to avoid long waiting times.

So I thought creating a growth table (using google dataStore) and... well I'm stucked there. How to solve that...

Any help appreciated !

答:
I just took a shot at this because you didn't have many responses...or any...that I saw.

```<code>from pandas_datareader import data

s = data.get_data_yahoo('SBUX', start='2016-01-02',end='2017-12-04')['Adj Close']
monthly = s.resample('BM', how=lambda x: x[-1])
print(monthly)
</code>```

Here is another way to get the time series data.

```<code>from pandas_datareader import data
import datetime as dt
import pandas as pd
ticker = 'MSFT'
begdate = '2016-11-11'
enddate = '2017-12-04'
data1 = data.DataReader(ticker,'yahoo',dt.datetime(2014,11,11),dt.datetime(2016,11,11))
print(data1)
</code>```

Below are some guidelines and overall rules of thumb.

When we make investments, we invest our money in different assets and earn returns for different periods of time. For example, an investment in a short-term Treasury bill will be for 3 months. We may invest in a stock and exit after a week for a few days. For the purpose of making the returns on these different investments comparable, we need to annualize the returns. So, all daily, weekly, monthly, or quarterly returns will be converted to annualized returns. The process for annualizing the returns is as follows:

The basic idea is to compound the returns to an annual period. So, if we have monthly returns, we know that there are 12 months in the year, similarly there are 52 weeks, 4 quarters, and 365 days. We compound our returns by the number of periods in the whole year.

Let’s take a few examples to understand this.

Example 1: Quarterly Returns

Let’s say we have 5% quarterly returns. Since there are four quarters in a year, the annual returns will be:

```<code>Annual returns = (1+0.05)^4 – 1 = 21.55%
</code>```

Example 2: Monthly Returns

Let’s say we have 2% monthly returns. Since there are 12 months in a year, the annual returns will be:

```<code>Annual returns = (1+0.02)^12 – 1 = 26.8%
</code>```

Example 3: Weekly Returns

Let’s say we have 0.5% weekly returns. Since there are 52 weeks in a year, the annual returns will be:

```<code>Annual returns = (1+0.005)^52 – 1 = 29.6%
</code>```

Example 4: Daily Returns

Let’s say we have 0.1% daily returns. Since there are 365 days in a year, the annual returns will be:

```<code>Annual returns = (1+0.001)^365 – 1 = 44.02%
</code>```

Example 5: 100 Days Returns

We can actually have returns for any number of days and convert them to annualized returns. Let’s say we have 6% returns over 100 days. The annual returns will be:

```<code>Annual returns = (1+0.06)^(365/100) – 1 = 23.69%
</code>```

Annualized returns however have one limitation – they assume that we will be able to reinvest the money at the same rate. However this may not always be possible. If we earned 5% in a quarter there is no guarantee that we will be able to replicate these returns over the next three quarters in the year.

Body:
I have a pretty complicated problem with absolutely no idea how to solve : I'm trying to calculate a daily/weekly/montlhy growth of some data.

The difficulty lies in the fact that I'm collecting data points randomly. So we can have data like that :

Date | orders

2017-01-12 |  1992
2017-01-13 |  2912
2017-02-10 |  3912
2017-02-11 |  4112
2017-02-12 |  4412
2017-02-16 |  5112
2017-03-01 |  8112

I have HUGE quantity of data, so I don't think it would be possible to actually build this without creating a temporary table that would store the results to avoid long waiting times.

So I thought creating a growth table (using google dataStore) and... well I'm stucked there. How to solve that...

Any help appreciated !

Body:
I just took a shot at this because you didn't have many responses...or any...that I saw.

from pandas_datareader import data

s = data.get_data_yahoo('SBUX', start='2016-01-02',end='2017-12-04')['Adj Close']
monthly = s.resample('BM', how=lambda x: x[-1])
print(monthly)

Here is another way to get the time series data.

from pandas_datareader import data
import datetime as dt
import pandas as pd
ticker = 'MSFT'
begdate = '2016-11-11'
enddate = '2017-12-04'
data1 = data.DataReader(ticker,'yahoo',dt.datetime(2014,11,11),dt.datetime(2016,11,11))
print(data1)

Below are some guidelines and overall rules of thumb.

When we make investments, we invest our money in different assets and earn returns for different periods of time. For example, an investment in a short-term Treasury bill will be for 3 months. We may invest in a stock and exit after a week for a few days. For the purpose of making the returns on these different investments comparable, we need to annualize the returns. So, all daily, weekly, monthly, or quarterly returns will be converted to annualized returns. The process for annualizing the returns is as follows:

The basic idea is to compound the returns to an annual period. So, if we have monthly returns, we know that there are 12 months in the year, similarly there are 52 weeks, 4 quarters, and 365 days. We compound our returns by the number of periods in the whole year.

Let’s take a few examples to understand this.

Example 1: Quarterly Returns

Let’s say we have 5% quarterly returns. Since there are four quarters in a year, the annual returns will be:

Annual returns = (1+0.05)^4 – 1 = 21.55%

Example 2: Monthly Returns

Let’s say we have 2% monthly returns. Since there are 12 months in a year, the annual returns will be:

Annual returns = (1+0.02)^12 – 1 = 26.8%

Example 3: Weekly Returns

Let’s say we have 0.5% weekly returns. Since there are 52 weeks in a year, the annual returns will be:

Annual returns = (1+0.005)^52 – 1 = 29.6%

Example 4: Daily Returns

Let’s say we have 0.1% daily returns. Since there are 365 days in a year, the annual returns will be:

Annual returns = (1+0.001)^365 – 1 = 44.02%

Example 5: 100 Days Returns

We can actually have returns for any number of days and convert them to annualized returns. Let’s say we have 6% returns over 100 days. The annual returns will be:

Annual returns = (1+0.06)^(365/100) – 1 = 23.69%

Annualized returns however have one limitation – they assume that we will be able to reinvest the money at the same rate. However this may not always be possible. If we earned 5% in a quarter there is no guarantee that we will be able to replicate these returns over the next three quarters in the year.


问:
Angular JS Application Unable to display data with wcf rest service
I am consuming wcf service into angular js application . I am trying to retrieve single record in angular js application . But the problem is its not display the data . I debug the application and the put the break point . It is not hitting sql data reader line code although i enter valid text in input filed . Its always execute connection .close method .

Here is the Interface.

```<code>   [OperationContract]

        [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/GetCustomers/{prefix}")]
        string GetCustomers(string prefix);
</code>```

Here is the Implementation .

```<code>   public string GetCustomers(string prefix)
        {

            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name LIKE @prefix + '%'";
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@prefix", prefix);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())// Hit on this line
                    {
                        while (sdr.Read())// Not hitting this line
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();// After reader hit this line
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }
</code>```

Here is the HTML CODE .

```<code>@{
    Layout = null;
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.IsVisible = false;
            $scope.Search = function () {
                var post = $http({
                    method: "POST",
                    url: "http://localhost:52098/HalifaxIISService.svc/GetCustomers/{prefix}",
                    dataType: 'json',
                    data: { prefix: $scope.Prefix },
                    headers: { "Content-Type": "application/json" }
                });

                post.success(function (data, status) {
                    $scope.Customers = eval(data.d);
                    $scope.IsVisible = true;
                });

                post.error(function (data, status) {
                    $window.alert(data.Message);
                });
            }
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Prefix" />
        <input type="button" value="Submit" ng-click="Search()" />
        <hr />
        <table cellpadding="0" cellspacing="0" ng-show="IsVisible">
            <tr style="height: 30px; background-color: skyblue; color: maroon;">
                <th> Account Number</th>
                <th>Account Creation date</th>
                <th>Account Type</th>
                <th> Sort code</th>
                <th>Account Fee</th>
                <th>Account Balance</th>
                <th>Overdraft Limit</th>

            </tr>
            <tbody ng-repeat="m in Customers">
                <tr>
                    <td>{{m.Tittle}}</td>
                    <td>{{m.Account_Holder_First_Name}}</td>
                    <td>{{m.Account_Holder_Last_Name}}</td>

                    <td>{{m.Account_Holder_DOB}}</td>
                    <td>{{m.Account_Holder_House_No}}</td>
                    <td>{{m.Account_Holder_Street_Name}}</td>
                    <td>{{m.Account_Holder_Post_Code}}</td>

                    <td>{{m.Account_Holder_Occupation}}</td>
                    <td>{{m.Account_Number}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>
</code>```

Here is the result of the application .

答:
Change it to this:</p>

```<code>var post = $http({
    method: "POST",
    url: "localhost:52098/HalifaxIISService.svc/GetCustomers",
    //dataType: 'json',
    data: { prefix: $scope.Prefix },
    //headers: { "Content-Type": "application/json" }
    headers: {
              'Accept': 'application/json, text/javascript, */*; q=0.01',
              'Content-Type': 'application/json; charset=utf-8'
            }
  });
</code>```

Body:
I am consuming wcf service into angular js application . I am trying to retrieve single record in angular js application . But the problem is its not display the data . I debug the application and the put the break point . It is not hitting sql data reader line code although i enter valid text in input filed . Its always execute connection .close method .

Here is the Interface.

   [OperationContract]

        [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/GetCustomers/{prefix}")]
        string GetCustomers(string prefix);

Here is the Implementation .

   public string GetCustomers(string prefix)
        {

            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name LIKE @prefix + '%'";
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@prefix", prefix);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())// Hit on this line
                    {
                        while (sdr.Read())// Not hitting this line
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();// After reader hit this line
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }

Here is the HTML CODE .

@{
    Layout = null;
}

    <title></title>

        Name:
        <input type="text" ng-model="Prefix" />
        <input type="button" value="Submit" ng-click="Search()" />

                 Account Number
                Account Creation date
                Account Type
                 Sort code
                Account Fee
                Account Balance
                Overdraft Limit

                    {{m.Tittle}}
                    {{m.Account_Holder_First_Name}}
                    {{m.Account_Holder_Last_Name}}

                    {{m.Account_Holder_DOB}}
                    {{m.Account_Holder_House_No}}
                    {{m.Account_Holder_Street_Name}}
                    {{m.Account_Holder_Post_Code}}

                    {{m.Account_Holder_Occupation}}
                    {{m.Account_Number}}

Here is the result of the application .

Body:
Change it to this:

var post = $http({
    method: "POST",
    url: "localhost:52098/HalifaxIISService.svc/GetCustomers",
    //dataType: 'json',
    data: { prefix: $scope.Prefix },
    //headers: { "Content-Type": "application/json" }
    headers: {
              'Accept': 'application/json, text/javascript, */*; q=0.01',
              'Content-Type': 'application/json; charset=utf-8'
            }
  });


问:
harmon.ie and Visio 2013 license error
I have outlook 2016 with MS Vision 2013 installed. When I try to open MS visio file from Harmon.ie, I get License error message.

Error:
Microsoft Office cannot verify the license for this product. You should repair the office program by using control panel.

I can open the MS same MS Visio drawing manually or from sharepoint with no problem.

答:
This error message could not be directly related to harmon.ie. You need to reach out to Microsoft about it. You should reproduce it out of harmon.ie.
Indeed, when user clicks on a document - harmon.ie (as a client application versus web interface) determines appropriate application based on the document extension and then launches the associated desktop application by passing it the URL to the document. Running the application from command line and passing it the direct URL of the Visio document duplicates the behavior of opening the document via harmon.ie. You can get the url to your Visio document by right clicking on it from our sidebar, and select copy address.
Please check again to see if running MS Visio, from command line and providing the URL to the SharePoint document would reproduce the issue:
-Open a cmd window
-Sample command format is below
"Path_to_Visio\visio_exe.exe" "urlof_document/document.visio_extension”

----- Jean

Title: harmon.ie and Visio 2013 license error


问:
How to use pandas groupby with aggregation for counting total time taken by a particular event for a particular ID?
Sample input:

```<code>    ID       Timestamp       Event
1   1   2010-05-31 13:43:45    a
2   1   2010-05-31 13:44:25    a
3   1   2010-05-31 13:44:55    a
4   1   2010-05-31 13:45:35    b
5   1   2010-05-31 13:47:05    b
6   1   2010-05-31 13:47:45    a
7   1   2010-05-31 13:49:45    c
8   1   2010-05-31 13:50:45    b
9   1   2010-06-01 09:20:00    c
10  1   2010-06-01 09:22:00    c
11  1   2010-06-01 09:23:20    c
12  1   2010-06-01 09:24:00    a
13  1   2010-06-01 09:24:15    a
14  1   2010-06-01 09:25:00    b
15  1   2010-06-01 09:25:42    b
16  2   2010-05-31 11:25:38    a
17  2   2010-05-31 11:26:00    c
18  2   2010-05-31 11:26:45    a
19  2   2010-05-31 11:27:10    a
20  2   2010-05-31 11:27:37    a
21  2   2010-05-31 11:29:35    b
22  2   2010-05-31 11:30:25    b
 .  .             .            .
 .  .             .            .
 .  .             .            .
</code>```

This is a pseudocode of what I'm currently doing, but its not working properly

```<code># Right now I'm looping through the dataframe, using this pseudocode:
for row in df.itertuples():
    check for ID match: (say, 1 == 1)
        check for event match: (say a == a)
           calculate time duration,
           check for < 3600
                store in a dictionary of the events ('a', 'b',etc = keys), cumulative
                store this  events dictionary for the ID
           else Increment session accordingly
        else
           store the previous occurrence time of the previous event,
           use it for the next occurrence of the event, using a dictionary;

           At the same time, find the current event's duration w.r.t.
           the time stored at the previous changing of the event(in the above line),
         again check for < 3600
                   store in a dictionary of the events ('a', 'b',etc = keys), cumulative
                   store this  events dictionary for the ID
       else Increment session accordingly
    else
        reset events dictionary to zero values
        reset the event change dictionary to zero values
</code>```

This is a sample output, but similar to what I want to do.

```<code>    ID   a_time   b_time   c_time   Session
1    1     120      200      100       2
2    2     235      340      145       3
.    .      .        .        .        .
.    .      .        .        .        .

Actually there are 7 unique events in all, I've just mentioned 3
to keep it less complicated.
</code>```

{Basically “a_time” = sum of time taken by all occurences the event ‘a’ for the current ID (if the time duration for that occurrence isn’t greater than 3600s; else increase the session count accordingly  session+time-duration/3600, OR by plus 1 only if the date changes as well)

‘’ = similar entry}

Hope:
Is there a more pythonic, or a vectorized way to do this? Like using

```<code>df.groupby(['ID'])['Timestamp'].diff()
</code>```

I used a lot of versions of this, but it didn't work for me, as I get "no aggregation function available for pd.groupby"

If I didn't need to use the time logs then I'd just use the command

```<code>df.groupby(['ID'])['Event'].value_counts().unstack().fillna(0)
</code>```

to get an output which would be the count of each of the unique events for each ID.

My obtained output, on using the pseudocode approach is just the repetition of the 1st row (just some random numbers shown here, not calculated) shown below, and I'm not able to see all the events as well, just three:

```<code>        ID       a_time       b_time       c_time
1       1         120          200           100
</code>```

Using groupby with ['Timestamp'].diff() as mentioned in the above part gives me error "no aggregation function available for pd.groupby". I even used sort_values, apply but I always got this same error (just mentioned in the above line).

答:
I solved it myself. I figured out that I could just use this:

```<code>df.at[index, col] = df.at[index, col] + duration
</code>```

Basically, as dataframe can visualized as a matrix, hence I still can access a dataframe by it's cell, so I managed to solve it.

Body:
Sample input:

    ID       Timestamp       Event
1   1   2010-05-31 13:43:45    a
2   1   2010-05-31 13:44:25    a
3   1   2010-05-31 13:44:55    a
4   1   2010-05-31 13:45:35    b
5   1   2010-05-31 13:47:05    b
6   1   2010-05-31 13:47:45    a
7   1   2010-05-31 13:49:45    c
8   1   2010-05-31 13:50:45    b
9   1   2010-06-01 09:20:00    c
10  1   2010-06-01 09:22:00    c
11  1   2010-06-01 09:23:20    c
12  1   2010-06-01 09:24:00    a
13  1   2010-06-01 09:24:15    a
14  1   2010-06-01 09:25:00    b
15  1   2010-06-01 09:25:42    b
16  2   2010-05-31 11:25:38    a
17  2   2010-05-31 11:26:00    c
18  2   2010-05-31 11:26:45    a
19  2   2010-05-31 11:27:10    a
20  2   2010-05-31 11:27:37    a
21  2   2010-05-31 11:29:35    b
22  2   2010-05-31 11:30:25    b
 .  .             .            .
 .  .             .            .
 .  .             .            .

This is a pseudocode of what I'm currently doing, but its not working properly

# Right now I'm looping through the dataframe, using this pseudocode:
for row in df.itertuples():
    check for ID match: (say, 1 == 1)
        check for event match: (say a == a)
           calculate time duration,
           check for < 3600
                store in a dictionary of the events ('a', 'b',etc = keys), cumulative
                store this  events dictionary for the ID
           else Increment session accordingly
        else
           store the previous occurrence time of the previous event,
           use it for the next occurrence of the event, using a dictionary;

           At the same time, find the current event's duration w.r.t.
           the time stored at the previous changing of the event(in the above line),
         again check for < 3600
                   store in a dictionary of the events ('a', 'b',etc = keys), cumulative
                   store this  events dictionary for the ID
       else Increment session accordingly
    else
        reset events dictionary to zero values
        reset the event change dictionary to zero values

This is a sample output, but similar to what I want to do.

    ID   a_time   b_time   c_time   Session
1    1     120      200      100       2
2    2     235      340      145       3
.    .      .        .        .        .
.    .      .        .        .        .

Actually there are 7 unique events in all, I've just mentioned 3
to keep it less complicated.

{Basically “a_time” = sum of time taken by all occurences the event ‘a’ for the current ID (if the time duration for that occurrence isn’t greater than 3600s; else increase the session count accordingly  session+time-duration/3600, OR by plus 1 only if the date changes as well)

‘’ = similar entry}

Hope:
Is there a more pythonic, or a vectorized way to do this? Like using

df.groupby(['ID'])['Timestamp'].diff()

I used a lot of versions of this, but it didn't work for me, as I get "no aggregation function available for pd.groupby"

If I didn't need to use the time logs then I'd just use the command

df.groupby(['ID'])['Event'].value_counts().unstack().fillna(0)

to get an output which would be the count of each of the unique events for each ID.

My obtained output, on using the pseudocode approach is just the repetition of the 1st row (just some random numbers shown here, not calculated) shown below, and I'm not able to see all the events as well, just three:

        ID       a_time       b_time       c_time
1       1         120          200           100

Using groupby with ['Timestamp'].diff() as mentioned in the above part gives me error "no aggregation function available for pd.groupby". I even used sort_values, apply but I always got this same error (just mentioned in the above line).

Body:
I solved it myself. I figured out that I could just use this:

df.at[index, col] = df.at[index, col] + duration

Basically, as dataframe can visualized as a matrix, hence I still can access a dataframe by it's cell, so I managed to solve it.


问:
Can't convert JSON string to Javascript object
I am trying to convert JSON string to javascript object, but unsuccessfully.

This is my code:

```<code>result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);
</code>```

I have created a fiddle with a demo.
https://jsfiddle.net/030u9z9f/1/

It seems like my JSON is not properly formatted, but I am not sure how to adjust it.

Body:
I am trying to convert JSON string to javascript object, but unsuccessfully.

This is my code:

result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);

I have created a fiddle with a demo.
https://jsfiddle.net/030u9z9f/1/

It seems like my JSON is not properly formatted, but I am not sure how to adjust it.

Body:
Try using this JSON,

{
"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg",
"sender": "Test test123",
"text": "Test 005",
"expiry": "2016-10-15 01:51:28",
"points": 650,
"color_from": "#8DBCC5",
"color_to": "#13717C"
}