问:
How to save many object (with the same class) to txt file and binding those object with listbox VB.NET
I try to program a simple project to save data to txt file, read it and use binding data to show it. My project like this.

When I add ID Person to "Add ID" textbox (Textbox which near Button "Add ID"). It will add ID to Listbox and "ID Name" textbox. With this IDName, I insert FirstName and LastName for first person and Save Person's Name. Then, I Add new ID in "Add ID" textbox and fill First,last name and save it again

I refer this page http://vbnetsample.blogspot.de/2007/12/serialize-deserialize-class-to-file.html?m=1 to save and read data to txt file. It's run ok. But my problem is that when I save Person 2 with ID 2, Person 1 is overwrited. I think I can save Person to List Person. But it will make difficult when I want to update any Person's data. I don't know whether Is there any way to save and update each person. And by the way How can I show data by binding data in listbox.

Here is my code

```<code>Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO

Public Class Form1
    Public pPerson As New Person

    'Serialize and Save Data to txt file
    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        pPerson.IDName = IDNameTextBox.Text
        pPerson.FirstName = FirstNameTextBox.Text
        pPerson.LastName = LastNameTextBox.Text
        Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter()
        bf.Serialize(fs, pPerson)
        fs.Close()
    End Sub

    'Deserialize and Read Data from txt file
    Private Sub ReadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadButton.Click
        If FileIO.FileSystem.FileExists("C:\Users\Bruce\Desktop\test.txt") Then
            Dim fsRead As New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Open)
            Dim bf As New BinaryFormatter()
            Dim objTest As Object = bf.Deserialize(fsRead)
            fsRead.Close()
            IDNameTextBox.Text = objTest.IDName
            FirstNameTextBox.Text = objTest.FirstName
            LastNameTextBox.Text = objTest.LastName
        End If
    End Sub

    Private Sub AddIDButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddIDButton.Click
        ListBox1.Items.Insert(0, AddIDTextBox.Text)
        IDNameTextBox.Text = AddIDTextBox.Text
    End Sub
End Class

'Create Class Person
<System.Serializable()>
Public Class Person
    Private m_sIDName As String
    Private m_sFirstName As String
    Private m_sLastName As String

    Public Sub New()
    End Sub
    Public Property IDName() As String
        Get
            Return Me.m_sIDName
        End Get
        Set(ByVal value As String)
            Me.m_sIDName = value
        End Set
    End Property

    Public Property FirstName() As String
        Get
            Return Me.m_sFirstName
        End Get
        Set(ByVal value As String)
            Me.m_sFirstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return Me.m_sLastName
        End Get
        Set(ByVal value As String)
            Me.m_sLastName = value
        End Set
    End Property

End Class
</code>```

答:
To me it seems like the issue here is

```<code>Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)
</code>```

you have to change it to this:

```<code>If not File.Exists("C:\Users\Bruce\Desktop\test.txt") Then
File.create("C:\Users\Bruce\Desktop\test.txt")
End If
Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Append)
</code>```

The whole problem was that your file was simply open (or created if it was not there before) and being written from the first line.By using FileMode.Append your File will be opened and anything new will be tried to be written at the end of the file.

Let me know if this worked :)

Body:
I try to program a simple project to save data to txt file, read it and use binding data to show it. My project like this.

When I add ID Person to "Add ID" textbox (Textbox which near Button "Add ID"). It will add ID to Listbox and "ID Name" textbox. With this IDName, I insert FirstName and LastName for first person and Save Person's Name. Then, I Add new ID in "Add ID" textbox and fill First,last name and save it again

I refer this page http://vbnetsample.blogspot.de/2007/12/serialize-deserialize-class-to-file.html?m=1 to save and read data to txt file. It's run ok. But my problem is that when I save Person 2 with ID 2, Person 1 is overwrited. I think I can save Person to List Person. But it will make difficult when I want to update any Person's data. I don't know whether Is there any way to save and update each person. And by the way How can I show data by binding data in listbox.

Here is my code

Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO

Public Class Form1
    Public pPerson As New Person

    'Serialize and Save Data to txt file
    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        pPerson.IDName = IDNameTextBox.Text
        pPerson.FirstName = FirstNameTextBox.Text
        pPerson.LastName = LastNameTextBox.Text
        Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter()
        bf.Serialize(fs, pPerson)
        fs.Close()
    End Sub

    'Deserialize and Read Data from txt file
    Private Sub ReadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadButton.Click
        If FileIO.FileSystem.FileExists("C:\Users\Bruce\Desktop\test.txt") Then
            Dim fsRead As New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Open)
            Dim bf As New BinaryFormatter()
            Dim objTest As Object = bf.Deserialize(fsRead)
            fsRead.Close()
            IDNameTextBox.Text = objTest.IDName
            FirstNameTextBox.Text = objTest.FirstName
            LastNameTextBox.Text = objTest.LastName
        End If
    End Sub

    Private Sub AddIDButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddIDButton.Click
        ListBox1.Items.Insert(0, AddIDTextBox.Text)
        IDNameTextBox.Text = AddIDTextBox.Text
    End Sub
End Class

'Create Class Person
<System.Serializable()>
Public Class Person
    Private m_sIDName As String
    Private m_sFirstName As String
    Private m_sLastName As String

    Public Sub New()
    End Sub
    Public Property IDName() As String
        Get
            Return Me.m_sIDName
        End Get
        Set(ByVal value As String)
            Me.m_sIDName = value
        End Set
    End Property

    Public Property FirstName() As String
        Get
            Return Me.m_sFirstName
        End Get
        Set(ByVal value As String)
            Me.m_sFirstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return Me.m_sLastName
        End Get
        Set(ByVal value As String)
            Me.m_sLastName = value
        End Set
    End Property

End Class

Body:
To me it seems like the issue here is

Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)

you have to change it to this:

If not File.Exists("C:\Users\Bruce\Desktop\test.txt") Then
File.create("C:\Users\Bruce\Desktop\test.txt")
End If
Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Append)

The whole problem was that your file was simply open (or created if it was not there before) and being written from the first line.By using FileMode.Append your File will be opened and anything new will be tried to be written at the end of the file.

Let me know if this worked :)


来源: stackexchange

问:
Windows EventLog: How fast are operations with it?
I have a service application that is processing client requests over TCP and writing any events into Windows EventLog. Since this application is expected to service many clients and lots of requests from each client in a short amount of time (let's say between 1 and 50 requests per second), I'm curious to know how intensive (CPU wise and time wise) and how fast can writing into Windows EventLog be?

More specifically, how intensive are the operations of connecting to, reading from and writing to EventLog?

答:
Event Tracing for Windows would likely be a better repository for this level of traffic.

Event Tracing for Windows (ETW) is an
  efficient kernel-level tracing
  facility that lets you log kernel or
  application-defined events to a log
  file. You can consume the events in
  real time or from a log file and use
  them to debug an application or to
  determine where performance issues are
  occurring in the application.

Sample pseudo-code:

```<code>const
    MyApplicationProviderGUID: TGUID = '{47A0DECE-4DCF-4782-BCF4-82AECA6BAAB7}';
private
   FETWRegistrationHandle: THandle;

...

EventRegister(MyApplicationProviderGUID, nil, nil, {out}FETWRegistrationHandle);
...
EventWriteString(FETWRegistrationHandle, 0, 0, 'Hello');
EventWriteString(FETWRegistrationHandle, 0, 0, ', ');
EventWriteString(FETWRegistrationHandle, 0, 0, 'world');
EventWriteString(FETWRegistrationHandle, 0, 0, '!');
...
EventUnregister(MyApplicationProviderGUID);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Event Tracing for Windows would likely be a better repository for this level of traffic.

Event Tracing for Windows (ETW) is an
  efficient kernel-level tracing
  facility that lets you log kernel or
  application-defined events to a log
  file. You can consume the events in
  real time or from a log file and use
  them to debug an application or to
  determine where performance issues are
  occurring in the application.

Sample pseudo-code:

const
    MyApplicationProviderGUID: TGUID = '{47A0DECE-4DCF-4782-BCF4-82AECA6BAAB7}';
private
   FETWRegistrationHandle: THandle;

...

EventRegister(MyApplicationProviderGUID, nil, nil, {out}FETWRegistrationHandle);
...
EventWriteString(FETWRegistrationHandle, 0, 0, 'Hello');
EventWriteString(FETWRegistrationHandle, 0, 0, ', ');
EventWriteString(FETWRegistrationHandle, 0, 0, 'world');
EventWriteString(FETWRegistrationHandle, 0, 0, '!');
...
EventUnregister(MyApplicationProviderGUID);

ContentLicense: CC BY-SA 3.0


Title: How to convert dictionary into multilevel dataframe?

Body:
Given:

A = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0],
              [5, 1, 4, -5, -4], [1, 5, 2, 2, -20], [2, 4, 4, 3, 0], [3, 3, 1, -1, -1],
              [4, 2, 2, 0, 0], [5, 1, 4, 20, -2]],
             columns=['a', 'b', 'c', 'd', 'e'],
             index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

B = pd.DataFrame([[0, 0, 0, 8, 2], [1, 1, 1, 1, 1], [0, 0, 0, 8, 2], [0, 0, 2, 1, 0],
              [5, 1, 4, -5, -4], [0, 0, 0, 8, 2], [2, 4, 4, 3, 0], [1, 3, 1, -1, -1],
              [1, 1, 2, 0, 0], [2, 2, 2, 20, -2]],
             columns=['a', 'b', 'c', 'd', 'e'],
             index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

test_list = [('test1', A), ('test2', B)]
d_test = dict(test_list)

Then I run into trouble when I try to convert this dictionary into a multi level dataframe. But I don't know how to specify the multilevel, I want the 'key' to be the name of the dataframe in the second level. This is the desired output

df

    test_1              test_2
    a   b   c   d   e   a   b   c   d   e
1   1   5   2   8   2   0   0   0   8   2
2   2   4   4   20  2   1   1   1   1   1
3   3   3   1   20  2   0   0   0   8   2
4   4   2   2   1   0   0   0   2   1   0
5   5   1   4   -5  -4  5   1   4   -5  -4
6   1   5   2   2   -20 0   0   0   8   2
7   2   4   4   3   0   2   4   4   3   0
8   3   3   1   -1  -1  1   3   1   -1  -1
9   4   2   2   0   0   1   1   2   0   0
10  5   1   4   20  -2  2   2   2   20  -2

Body:
Just for the purpose of having here an answer
(which was already given in the comments) here it goes (again):

import pandas as pd
A = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0],
              [5, 1, 4, -5, -4], [1, 5, 2, 2, -20], [2, 4, 4, 3, 0], [3, 3, 1, -1, -1],
              [4, 2, 2, 0, 0], [5, 1, 4, 20, -2]],
             columns=['a', 'b', 'c', 'd', 'e'],
             index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
B = pd.DataFrame([[0, 0, 0, 8, 2], [1, 1, 1, 1, 1], [0, 0, 0, 8, 2], [0, 0, 2, 1, 0],
              [5, 1, 4, -5, -4], [0, 0, 0, 8, 2], [2, 4, 4, 3, 0], [1, 3, 1, -1, -1],
              [1, 1, 2, 0, 0], [2, 2, 2, 20, -2]],
             columns=['a', 'b', 'c', 'd', 'e'],
             index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
AB=pd.concat([A,B], axis=1)
header = ['test1','test1','test1','test1','test1','test2','test2','test2','test2','test2']
AB.columns = pd.MultiIndex.from_tuples(list(zip(header, AB.columns)))
print(AB) # gives what was asked for
print("test1: \n", AB.test1) # gives A
print("test2: \n", AB.test2) # gives B

Another (down to real life situation) way of achieving the same (answer given in the above comments):

test_list = [('test1', A), ('test2', B)]
d_test = dict(test_list)
AB = pd.concat(d_test.values(), keys=d_test.keys(), axis=1)
# what means: AB = pd.concat([A,B], keys=['test1', 'test2'], axis=1)

The code above outputs:

   test1               test2
       a  b  c   d   e     a  b  c   d  e
1      1  5  2   8   2     0  0  0   8  2
2      2  4  4  20   2     1  1  1   1  1
3      3  3  1  20   2     0  0  0   8  2
4      4  2  2   1   0     0  0  2   1  0
5      5  1  4  -5  -4     5  1  4  -5 -4
6      1  5  2   2 -20     0  0  0   8  2
7      2  4  4   3   0     2  4  4   3  0
8      3  3  1  -1  -1     1  3  1  -1 -1
9      4  2  2   0   0     1  1  2   0  0
10     5  1  4  20  -2     2  2  2  20 -2
test1:
     a  b  c   d   e
1   1  5  2   8   2
2   2  4  4  20   2
3   3  3  1  20   2
4   4  2  2   1   0
5   5  1  4  -5  -4
6   1  5  2   2 -20
7   2  4  4   3   0
8   3  3  1  -1  -1
9   4  2  2   0   0
10  5  1  4  20  -2
test2:
     a  b  c   d  e
1   0  0  0   8  2
2   1  1  1   1  1
3   0  0  0   8  2
4   0  0  2   1  0
5   5  1  4  -5 -4
6   0  0  0   8  2
7   2  4  4   3  0
8   1  3  1  -1 -1
9   1  1  2   0  0
10  2  2  2  20 -2


问:
Boost regex to capture all repeated patterns
I have a simple text file with the following contents:

```<code>VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"
</code>```

The values in column 1 are known.

I want to capture everything in column 1 and in column 2.

My solution involves manually writing all the possible values of column 1 (which is known), into the regex string but obviously this is not ideal practice since I am basically repeating code and this does not allow the ordering to be flexible:

```<code>const char* re =
     "^[[:space:]]*"
     "(VALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(ANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(YETANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*";
</code>```

答:
I'm citing commenter Igor Tandetnik here, because he almost gave the complete answer in his comment:

Regular expressions capture exactly as many substrings as there are
left parentheses in the expression [...]

The right way to solve this problem is to write a regex that matches a
single pair, [...]

```<code>\s*([a-zA-Z]+)\s*"(.*?)"
</code>```

Notes:

\s is equivalent to [[:space:]]

.*? is used to stop searching after the 2nd " instead of the last " in the string

and apply it repeatedly, e.g. via std::regex_iterator

The boost equivalent is boost::regex_iterator.

```<code>#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>

const boost::regex expr{ R"__(\s*([a-zA-Z]+)\s*"(.*?)")__" };

const std::string s =
R"(VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"
)";

int main() {
    boost::sregex_iterator it{ begin(s), end(s), expr }, itEnd;

    std::for_each( it, itEnd, []( const boost::smatch& m ){
        std::cout << m[1] << '\n' << m[2] << std::endl;
    });
}
</code>```

Live demo.

Notes:

I'm using raw string literals to make the code cleaner.

Body:
I have a simple text file with the following contents:

VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"

The values in column 1 are known.

I want to capture everything in column 1 and in column 2.

My solution involves manually writing all the possible values of column 1 (which is known), into the regex string but obviously this is not ideal practice since I am basically repeating code and this does not allow the ordering to be flexible:

const char* re =
     "^[[:space:]]*"
     "(VALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(ANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(YETANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*";

Body:
I'm citing commenter Igor Tandetnik here, because he almost gave the complete answer in his comment:

Regular expressions capture exactly as many substrings as there are
left parentheses in the expression [...]

The right way to solve this problem is to write a regex that matches a
single pair, [...]

\s*([a-zA-Z]+)\s*"(.*?)"

Notes:

\s is equivalent to [[:space:]]

.*? is used to stop searching after the 2nd " instead of the last " in the string

and apply it repeatedly, e.g. via std::regex_iterator

The boost equivalent is boost::regex_iterator.

#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>

const boost::regex expr{ R"__(\s*([a-zA-Z]+)\s*"(.*?)")__" };

const std::string s =
R"(VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"
)";

int main() {
    boost::sregex_iterator it{ begin(s), end(s), expr }, itEnd;

    std::for_each( it, itEnd, []( const boost::smatch& m ){
        std::cout << m[1] << '\n' << m[2] << std::endl;
    });
}

Live demo.

Notes:

I'm using raw string literals to make the code cleaner.


问:
React - using deep equality as to not re-render on object identity change
React discusses on this page about performance that you can use shallow equality and avoid mutating objects, so that components need only to check references to see if props or state changed.

I'm actually wondering about the opposite: is it possible to have the equality check use deep equality and ignore when the object references change (as long as their contents don't change)?

Reason is, I have a library which returns a cloned version of some internal variables, and to see updates on those variables, I need to re-ask for that internal variable, thus getting a fresh new clone. So I'll get entirely different objects by reference, but they could have not changed any of their fields. But every time I request such an update, React thinks everything has changed because all the references changed, and it re-renders a lot of unnecessary stuff.

Current solution: threw this in a component to stop it from rendering as long as the objects' fields don't change

```<code>shouldComponentUpdate(nextProps, nextState) {
  return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState);
}
</code>```

which does the trick since lodash's isEqual equality check is deep, but I'd have to do that on each component that wants this behavior. I wonder if there's either a

preferred way of achieving this

an anti-pattern I'm using which leads to this in the first place and I could avoid it entirely

or maybe the above method is best.

答:
I would not suggest you do this for the following reasons:

Deep comparisons are costly. So everytime something changes you will have to do a deep comparison and then do the rendering part. We would just be better off letting react do the rendering cause it was made for it.

As for the case of handling it in all the components. We can avoid this problem by destructuring the object thus sending smaller props, now the react can handle the optimised re-renders. eg:

I hope that helps!

Body:
React discusses on this page about performance that you can use shallow equality and avoid mutating objects, so that components need only to check references to see if props or state changed.

I'm actually wondering about the opposite: is it possible to have the equality check use deep equality and ignore when the object references change (as long as their contents don't change)?

Reason is, I have a library which returns a cloned version of some internal variables, and to see updates on those variables, I need to re-ask for that internal variable, thus getting a fresh new clone. So I'll get entirely different objects by reference, but they could have not changed any of their fields. But every time I request such an update, React thinks everything has changed because all the references changed, and it re-renders a lot of unnecessary stuff.

Current solution: threw this in a component to stop it from rendering as long as the objects' fields don't change

shouldComponentUpdate(nextProps, nextState) {
  return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState);
}

which does the trick since lodash's isEqual equality check is deep, but I'd have to do that on each component that wants this behavior. I wonder if there's either a

preferred way of achieving this

an anti-pattern I'm using which leads to this in the first place and I could avoid it entirely

or maybe the above method is best.

Body:
I would not suggest you do this for the following reasons:

Deep comparisons are costly. So everytime something changes you will have to do a deep comparison and then do the rendering part. We would just be better off letting react do the rendering cause it was made for it.

As for the case of handling it in all the components. We can avoid this problem by destructuring the object thus sending smaller props, now the react can handle the optimised re-renders. eg:

<Footer data={object} />

<Footer title={object.title} copyright={object.copyright}/>

I hope that helps!


问:
My regex is returning nil everytime in obj-c, example code included
edit i clarified exactly what text im getting stored in a string.

So heres my regex https://regex101.com/r/fWFRya/5 -this had the wrong string zz, thats why everyone was confused my mistake it is fixed now see again

```<code>^.*?".*?:\s+(?|(?:(.*?[!.?])\s+.*?)|(.*?))".*$
</code>```

heres how it looks in my code, backslashes added to escape quotes

```<code>NSString *regexTweet = @"^.*?\".*?:\\s+(?|(?:(.*?[!.?])\\s+.*?)|(.*?))\".*$";
//the example string contains the text>   @user hey heres my message: first message: and a second colon! haha.
      NSString *example1 = @"@user hey heres my message: first message: and a second colon! haha.";
  NSError *regexerror = nil;
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexTweet options:NSRegularExpressionCaseInsensitive error:&regexerror];

  NSRange range = [regex rangeOfFirstMatchInString:example1
  options:0
  range:NSMakeRange(0, [example1 length])];
  NSString *final1 = [example1 substringWithRange:range];
  HBLogDebug (@"example 1 has become %@", final1);
</code>```

when I log final1 it always returns nil and i'm unable to figure out where it's going wrong, I would appreciate if someone could give me a hand

expected output is

first message: and a second colon!

答:
First of all, you created a regex for NSString *example1 = @("@user hey heres my message: first message: and a second colon! haha");, but the string you pass to the regex engine in the code is @user hey heres my message: first message: and a second colon! haha.

I assume that you need to match a string like Text.. "@user hey heres my message: first message: and a second colon! haha".

Note that ICU regex  library does not support Branch Reset Groups.

I suggest changing the branch reset group into a capturing group with an alternation group:

```<code>^.*?:\s+(.*?[!.?](?=\s)|[^"]*).*$
</code>```

See the regex demo

Details:

^ - start of the string

.*?: - any 0+ chars up to the first : that is followed with

\s+  - 1 or more whitespaces...

(.*?[!.?](?=\s)|[^"]*)  - Group 1 capturing either

.*?[!.?](?=\s) - any 0+ chars as few as possible up to the first !, . or ? that are followed with whitespace

| - or

[^"]* - zero or more chars other than "

.*$  - any 0+ chars up to the end of string

All you need is to access Group 1 to get the value you need. See a sample Objective-C demo.

Body:
edit i clarified exactly what text im getting stored in a string.

So heres my regex https://regex101.com/r/fWFRya/5 -this had the wrong string zz, thats why everyone was confused my mistake it is fixed now see again

^.*?".*?:\s+(?|(?:(.*?[!.?])\s+.*?)|(.*?))".*$

heres how it looks in my code, backslashes added to escape quotes

NSString *regexTweet = @"^.*?\".*?:\\s+(?|(?:(.*?[!.?])\\s+.*?)|(.*?))\".*$";
//the example string contains the text>   @user hey heres my message: first message: and a second colon! haha.
      NSString *example1 = @"@user hey heres my message: first message: and a second colon! haha.";
  NSError *regexerror = nil;
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexTweet options:NSRegularExpressionCaseInsensitive error:&regexerror];

  NSRange range = [regex rangeOfFirstMatchInString:example1
  options:0
  range:NSMakeRange(0, [example1 length])];
  NSString *final1 = [example1 substringWithRange:range];
  HBLogDebug (@"example 1 has become %@", final1);

when I log final1 it always returns nil and i'm unable to figure out where it's going wrong, I would appreciate if someone could give me a hand

expected output is

first message: and a second colon!

Body:
First of all, you created a regex for NSString *example1 = @("@user hey heres my message: first message: and a second colon! haha");, but the string you pass to the regex engine in the code is @user hey heres my message: first message: and a second colon! haha.

I assume that you need to match a string like Text.. "@user hey heres my message: first message: and a second colon! haha".

Note that ICU regex  library does not support Branch Reset Groups.

I suggest changing the branch reset group into a capturing group with an alternation group:

^.*?:\s+(.*?[!.?](?=\s)|[^"]*).*$

See the regex demo

Details:

^ - start of the string

.*?: - any 0+ chars up to the first : that is followed with

\s+  - 1 or more whitespaces...

(.*?[!.?](?=\s)|[^"]*)  - Group 1 capturing either

.*?[!.?](?=\s) - any 0+ chars as few as possible up to the first !, . or ? that are followed with whitespace

| - or

[^"]* - zero or more chars other than "

.*$  - any 0+ chars up to the end of string

All you need is to access Group 1 to get the value you need. See a sample Objective-C demo.


问:
How to insert current date to a curl command?
I'm trying to insert today's date to my curl command but I can't get the date command to display the correct date.

```<code>root@elk01:~# curl -s -XGET 'http://localhost:9200/"$(date -u +%Y.%m.%d)"/_search?pretty'
{
    "error":
        {"root_cause":
            [
                {"type":"illegal_argument_exception","reason" : "invalid version format: -U +%Y.%M.%D)\"/_SEARCH?PRETTY HTTP/1.1"}
            ],
                "type":"illegal_argument_exception","reason":"invalid version format: -U +%Y.%M.%D)\"/_SEARCH?PRETTY HTTP/1.1"
        },
    "status":400
}
</code>```

I've tried:

```<code>curl -s -XGET 'http://localhost:9200/"$(date -u +%Y.%m.%d)"/_search?pretty'
curl -s -XGET 'http://localhost:9200/\"$(date -u +%Y.%m.%d)\"/_search?prett
y'
curl -s -XGET "http://localhost:9200/\$(date -u +%Y.%m.%d)/_search?prett
y"
</code>```

But none of them actually use the result of date -u +%Y.%m.%d.

答:
Following command did the job for me:</p>

```<code>curl -XGET "http://localhost:9200/`date -u +%Y.%m.%d`/_search" -d '
{
    "query": {
        "match_all": {}
    }
}'
</code>```

Body:
I'm trying to insert today's date to my curl command but I can't get the date command to display the correct date.

root@elk01:~# curl -s -XGET 'http://localhost:9200/"$(date -u +%Y.%m.%d)"/_search?pretty'
{
    "error":
        {"root_cause":
            [
                {"type":"illegal_argument_exception","reason" : "invalid version format: -U +%Y.%M.%D)\"/_SEARCH?PRETTY HTTP/1.1"}
            ],
                "type":"illegal_argument_exception","reason":"invalid version format: -U +%Y.%M.%D)\"/_SEARCH?PRETTY HTTP/1.1"
        },
    "status":400
}

I've tried:

curl -s -XGET 'http://localhost:9200/"$(date -u +%Y.%m.%d)"/_search?pretty'
curl -s -XGET 'http://localhost:9200/\"$(date -u +%Y.%m.%d)\"/_search?prett
y'
curl -s -XGET "http://localhost:9200/\$(date -u +%Y.%m.%d)/_search?prett
y"

But none of them actually use the result of date -u +%Y.%m.%d.

Body:
Following command did the job for me:

curl -XGET "http://localhost:9200/`date -u +%Y.%m.%d`/_search" -d '
{
    "query": {
        "match_all": {}
    }
}'


问:
dynamically create element with onclick
I'm obviously missing something, but I haven't been able to find what I am doing wrong and I have been staring at this for entirely too long

```<code>function message(options) {
  ...
  options.onclose = options.onclose || null;
  ...
  this.gui = document.createElement('div');
  this.msg = document.createElement('div');
  ...
  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'close';
    close.className = 'material-icons close';
    close.onclick = options.onclose;
    console.log(close.onclick);
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);
  ...
  return this.gui;
}

msgContainer.append(new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  }));
</code>```

from the developer console document.querySelector('.close').onclick is null, but if I add an on click document.querySelector('.close').onclick = () => { console.log('click'); }; it works?

答:
Here is working example. I changed your code a little bit. You can add more events by passing it to an array. I used addEventListener.

var msgContainer = document.getElementById('msgContainer');

function message(options) {

  options.onclose = options.onclose || null;

  this.gui = document.createElement('div');
  this.msg = document.createElement('div');

  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'closepp';
    close.className = 'material-icons close';
    close.dataset.action = 'close';
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);

  // Create listeners dynamically later on
  events = [
   { selector: close.dataset.action, eventType: 'click', event: options.onclose }
  ];

  renderElement(this.gui, events);
}

function renderElement(element, events) {
 msgContainer.append(element);

  for (i = 0; i < events.length; i++) {
   var currentEvent = events[i];
        var selector = element.querySelector('[data-action="' + currentEvent['selector'] + '"]');

   selector.addEventListener(currentEvent['eventType'], currentEvent['event'].bind(this), false);
  }
}

new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="msgContainer">

</div></code>```

Title: dynamically create element with onclick

Body:
I'm obviously missing something, but I haven't been able to find what I am doing wrong and I have been staring at this for entirely too long

function message(options) {
  ...
  options.onclose = options.onclose || null;
  ...
  this.gui = document.createElement('div');
  this.msg = document.createElement('div');
  ...
  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'close';
    close.className = 'material-icons close';
    close.onclick = options.onclose;
    console.log(close.onclick);
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);
  ...
  return this.gui;
}

msgContainer.append(new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  }));

from the developer console document.querySelector('.close').onclick is null, but if I add an on click document.querySelector('.close').onclick = () => { console.log('click'); }; it works?

Body:
Here is working example. I changed your code a little bit. You can add more events by passing it to an array. I used addEventListener.

var msgContainer = document.getElementById('msgContainer');

function message(options) {

  options.onclose = options.onclose || null;

  this.gui = document.createElement('div');
  this.msg = document.createElement('div');

  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'closepp';
    close.className = 'material-icons close';
    close.dataset.action = 'close';
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);

  // Create listeners dynamically later on
  events = [
   { selector: close.dataset.action, eventType: 'click', event: options.onclose }
  ];

  renderElement(this.gui, events);
}

function renderElement(element, events) {
 msgContainer.append(element);

  for (i = 0; i < events.length; i++) {
   var currentEvent = events[i];
        var selector = element.querySelector('[data-action="' + currentEvent['selector'] + '"]');

   selector.addEventListener(currentEvent['eventType'], currentEvent['event'].bind(this), false);
  }
}

new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  });

<div id="msgContainer">

</div>


问:
How to get a list of users from Slack API using BotKit?
I'm trying to create a bot that sends a direct message to a random slack user. The first step I am trying to accomplish is console.logging the list of users.

Here is what I have so far:

```<code>controller.hears('marco', 'direct_message', function(bot, message) {
  bot.api.users.list({user: message.user}, function(err, list){
    bot.reply(message, "polo");
    console.log(bot.api.users.list);
  })
});
</code>```

When I direct message the bot marco, it replies polo and [Function] is logged. How am able to log some real data? I tried bot.api.users.list.members, but it logs as undefined. Thank you.

答:
If you want to list ALL users, you are using a correct API call, just remove the params from it ({} instead of {user: message.user}).
Docs: users.list

If you want to get information about a specific user from your team, you should use the following API call: bot.api.users.info({ user: USER_ID }, function (err, response) { ... });
Docs: users.info

There's also a test section in the Slack docs ('Tester' tab) so that you can try out what the API calls will return for your actual users.

Body:
I'm trying to create a bot that sends a direct message to a random slack user. The first step I am trying to accomplish is console.logging the list of users.

Here is what I have so far:

controller.hears('marco', 'direct_message', function(bot, message) {
  bot.api.users.list({user: message.user}, function(err, list){
    bot.reply(message, "polo");
    console.log(bot.api.users.list);
  })
});

When I direct message the bot marco, it replies polo and [Function] is logged. How am able to log some real data? I tried bot.api.users.list.members, but it logs as undefined. Thank you.


问:
Interpret Scala syntax for varargs

Possible Duplicate:

  Syntax sugar: _*

I wrote a function that gets passed a format string (for String.format(...)) and a varargs array of parameters (among other things). The method looks like this:

```<code>def myMethod(foo: Number, formatStr: String, params: Any*): Unit = {
  // .. some stuff with foo
  println(formatStr, params.map(_.asInstanceOf[AnyRef]) : _*)
}
</code>```

I got the syntax for the params argument here. It works! But how? I do not understand the syntax of the second argument to println, particularly the ending part (: _*). It is obviously calling map and expanding the array to a sequence of AnyRefs.

答:
Generally, the : notation is used for type ascription, forcing the compiler to see a value as some particular type.  This is not quite the same as casting.

```<code>val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double
</code>```

In this case, you're ascribing the special varargs type _*.  This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses Seq[T]:

```<code>def myMethod(params: Any*) = ... //varargs parameter, use as an Array[Any]

val list = Seq("a", 42, 3.14) //a Seq[Any]
myMethod(list : _*)
</code>```

Title: Interpret Scala syntax for varargs

Body:
Possible Duplicate:

  Syntax sugar: _*

I wrote a function that gets passed a format string (for String.format(...)) and a varargs array of parameters (among other things). The method looks like this:

def myMethod(foo: Number, formatStr: String, params: Any*): Unit = {
  // .. some stuff with foo
  println(formatStr, params.map(_.asInstanceOf[AnyRef]) : _*)
}

I got the syntax for the params argument here. It works! But how? I do not understand the syntax of the second argument to println, particularly the ending part (: _*). It is obviously calling map and expanding the array to a sequence of AnyRefs.

Body:
Generally, the : notation is used for type ascription, forcing the compiler to see a value as some particular type.  This is not quite the same as casting.

val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double

In this case, you're ascribing the special varargs type _*.  This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses Seq[T]:

def myMethod(params: Any*) = ... //varargs parameter, use as an Array[Any]

val list = Seq("a", 42, 3.14) //a Seq[Any]
myMethod(list : _*)


问:
electron, after browserify, fs.existsSync is not a function
i read a lot about browserify and electron and the gui browser issue
yet there is still a problem with  browserify, saying "fs.existsSync is not a function", and "required is not defined"

* The full story*
i created simple gui with electron   ,
there are the package.json file, the main.js and the index.html file + 3,4 html files, where there i want to create simple "load show save window" that work with require

That feature worked in the index.html file yet doesn't work properly in the load.html file, so i browserify the main.js with the commands

var  fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote ```
</div>
</div>
 </p>

<p>into main.bundle3.js, with, (in the cmd)</p>

```browserify main.js > main.bundle3.js
```

<p>yet then the load.html file shouted that require is not define and    </p>

```> main.bundle3.js:6945 Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (main.bundle3.js:6945)
    at Object.require.36.fs (main.bundle3.js:6951)
    at s (main.bundle3.js:1)
    at main.bundle3.js:1
    at Object.<anonymous> (main.bundle3.js:6794)
    at Object.require.35._process (main.bundle3.js:6937)
    at s (main.bundle3.js:1)
    at e (main.bundle3.js:1)
    at main.bundle3.js:1
(anonymous) @   main.bundle3.js:6945
require.36.fs   @   main.bundle3.js:6951
s   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:6794
require.35._process @   main.bundle3.js:6937
s   @   main.bundle3.js:1
e   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
```

<p>The package.json</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "RDF",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "test": "mocha -u exports -R spec test/index"
  },
  "devDependencies": {
    "electron": "^1.6.2",
    "electron-packager": "^8.6.0",
    "html-browserify": "0.0.6",
    "jquery": "^3.2.1"
  }
}</code>```

 and load.html file

<!DOCTYPE html>

    <meta charset="UTF-8">

LOAD

load the data

            <input type="text" placeholder="just select a file" id="actual-file" disabled="disabled"/>
            <input type="button" value="Choose a file" id="select-file"/>

        <textarea id="content-editor" rows="5"></textarea>

        <input type="button" id="save-changes" value="Save changes"/>
        <input type="button" id="delete-file" value="Delete file"/>

  he file content will be the same as the editor.

        <input type="button" value="Choose a file" id="create-new-file"/>

```
</div>
</div>
</p>

<p>the the main.js file in full</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//console.log(require('fs'));
console.log(require('module').globalPaths);
const {
  electron
} = require('electron');
const {
  BrowserWindow
} = require('electron')
const {
  app
} = require('electron');
//  @show(app)
const path = require('path')
//console.log( process.env.PATH);
// (D:\electron-v1.6.1-win32-x64\resources\default_app.asr\main.js:325:5)
 //const BrowserWindow = require('browser-window')
const url = require('url')
var html = require('html-browserify');
var fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote
//dialog = require('electron').dialog
//dialog =remote.require('dialog')

//var load_=require('./load_.js')
// broserify html
var through = require('through');
var htmlclean = require('htmlclean');

module.exports = function(file, options) {

  options = options || {};
  options.htmlclean =
   typeof options.htmlclean !== 'undefined'
      ?      options.htmlclean : true;

  var buffer = '';

  if (!/\.(tpl|html)/.test(file)) {

    return through();

  } else {

    return through(function(chunk) {

      return buffer += chunk.toString();

    }, function() {

      var jst = buffer.toString();

      if (options.htmlclean) {
        //options.htmlclean is truthy

        if (typeof options.htmlclean === 'object') {
          //options.htmlclean is an options object for the htmlclean module
          jst = htmlclean(jst, options.htmlclean);
        } else {
          //otherwise, clean using default options
          jst = htmlclean(jst);
        }
      }

      var compiled = 'module.exports = ';
      compiled += JSON.stringify(jst);
      compiled += ';\n';

      this.queue(compiled);
      return this.queue(null);

    });

  }

}
//requirejs.config({
//By default load any module IDs from js/lib
//  baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
//paths: {
//  app: '  '
//}
//});

// Start the main app logic.
//requirejs(['jquery', 'canvas', 'app/sub'],
//function   ($,        canvas,   sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
//});
//const fs = require('fs');
//const app = require('electron').app.
//const remote = require('electron').remote;

// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1050,
    height: 814
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.</code>```

答:
*** the technical solution is to link files one after the others from the index.html file, where in each there are js files that work with require

*** the error "fs.existsSync is not a function" is general error. appearing where there are problems with require() in files that are not connected directly to the main files (index.html and main.js)

*** all the other solutions failed (many appear in the internet from browserify, webpack, webview, requirejs, and others)

Body:
i read a lot about browserify and electron and the gui browser issue
yet there is still a problem with  browserify, saying "fs.existsSync is not a function", and "required is not defined"

* The full story*
i created simple gui with electron   ,
there are the package.json file, the main.js and the index.html file + 3,4 html files, where there i want to create simple "load show save window" that work with require

That feature worked in the index.html file yet doesn't work properly in the load.html file, so i browserify the main.js with the commands

var  fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote

into main.bundle3.js, with, (in the cmd)

browserify main.js > main.bundle3.js

yet then the load.html file shouted that require is not define and

> main.bundle3.js:6945 Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (main.bundle3.js:6945)
    at Object.require.36.fs (main.bundle3.js:6951)
    at s (main.bundle3.js:1)
    at main.bundle3.js:1
    at Object.<anonymous> (main.bundle3.js:6794)
    at Object.require.35._process (main.bundle3.js:6937)
    at s (main.bundle3.js:1)
    at e (main.bundle3.js:1)
    at main.bundle3.js:1
(anonymous) @   main.bundle3.js:6945
require.36.fs   @   main.bundle3.js:6951
s   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:6794
require.35._process @   main.bundle3.js:6937
s   @   main.bundle3.js:1
e   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1

The package.json

{
  "name": "RDF",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "test": "mocha -u exports -R spec test/index"
  },
  "devDependencies": {
    "electron": "^1.6.2",
    "electron-packager": "^8.6.0",
    "html-browserify": "0.0.6",
    "jquery": "^3.2.1"
  }
}

 and load.html file

<!DOCTYPE html>

    <meta charset="UTF-8">

LOAD

load the data

            <input type="text" placeholder="just select a file" id="actual-file" disabled="disabled"/>
            <input type="button" value="Choose a file" id="select-file"/>

        <textarea id="content-editor" rows="5"></textarea>

        <input type="button" id="save-changes" value="Save changes"/>
        <input type="button" id="delete-file" value="Delete file"/>

  he file content will be the same as the editor.

        <input type="button" value="Choose a file" id="create-new-file"/>

the the main.js file in full

//console.log(require('fs'));
console.log(require('module').globalPaths);
const {
  electron
} = require('electron');
const {
  BrowserWindow
} = require('electron')
const {
  app
} = require('electron');
//  @show(app)
const path = require('path')
//console.log( process.env.PATH);
// (D:\electron-v1.6.1-win32-x64\resources\default_app.asr\main.js:325:5)
 //const BrowserWindow = require('browser-window')
const url = require('url')
var html = require('html-browserify');
var fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote
//dialog = require('electron').dialog
//dialog =remote.require('dialog')

//var load_=require('./load_.js')
// broserify html
var through = require('through');
var htmlclean = require('htmlclean');

module.exports = function(file, options) {

  options = options || {};
  options.htmlclean =
   typeof options.htmlclean !== 'undefined'
      ?      options.htmlclean : true;

  var buffer = '';

  if (!/\.(tpl|html)/.test(file)) {

    return through();

  } else {

    return through(function(chunk) {

      return buffer += chunk.toString();

    }, function() {

      var jst = buffer.toString();

      if (options.htmlclean) {
        //options.htmlclean is truthy

        if (typeof options.htmlclean === 'object') {
          //options.htmlclean is an options object for the htmlclean module
          jst = htmlclean(jst, options.htmlclean);
        } else {
          //otherwise, clean using default options
          jst = htmlclean(jst);
        }
      }

      var compiled = 'module.exports = ';
      compiled += JSON.stringify(jst);
      compiled += ';\n';

      this.queue(compiled);
      return this.queue(null);

    });

  }

}
//requirejs.config({
//By default load any module IDs from js/lib
//  baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
//paths: {
//  app: '  '
//}
//});

// Start the main app logic.
//requirejs(['jquery', 'canvas', 'app/sub'],
//function   ($,        canvas,   sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
//});
//const fs = require('fs');
//const app = require('electron').app.
//const remote = require('electron').remote;

// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1050,
    height: 814
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.


问:
The ${^MATCH} and the /p modifier in perl v24
The perlre says:

p

Preserve the string matched such that ${^PREMATCH} , ${^MATCH} , and
  ${^POSTMATCH} are available for use after matching.

In Perl 5.20 and higher this is ignored. Due to a new copy-on-write
  mechanism, ${^PREMATCH} , ${^MATCH} , and ${^POSTMATCH} will be
  available after the match regardless of the modifier.

also the perlvar

${^MATCH}
  This is similar to $& ($MATCH ) except that it does not incur the
  performance penalty associated with that variable.

In Perl v5.18 and earlier, it is only guaranteed to return a defined
  value when the pattern was compiled or executed with the /p modifier.
  In Perl v5.20, the /p modifier does nothing, so ${^MATCH} does the same thing as $MATCH .

test:

```<code>echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/g'
</code>```

output: two empty lines (2x \n)

but the:

```<code>echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/gp'
</code>```

output:

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

My perl:

```<code>$ perl -v

This is perl 5, version 24, subversion 0 (v5.24.0) built for darwin-2level
(with 1 registered patch, see perl -V for more detail)
</code>```

So in the 5.24.0 the /p modifier is still needed? Or what me missed?

答:
There is indeed a discrepancy between the code's behaviour and the documented behaviour. Filed a bug report as ticket RT#131087.

As a workaround, you can use use $& ($MATCH).

Body:
The perlre says:

p

Preserve the string matched such that ${^PREMATCH} , ${^MATCH} , and
  ${^POSTMATCH} are available for use after matching.

In Perl 5.20 and higher this is ignored. Due to a new copy-on-write
  mechanism, ${^PREMATCH} , ${^MATCH} , and ${^POSTMATCH} will be
  available after the match regardless of the modifier.

also the perlvar

${^MATCH}
  This is similar to $& ($MATCH ) except that it does not incur the
  performance penalty associated with that variable.

In Perl v5.18 and earlier, it is only guaranteed to return a defined
  value when the pattern was compiled or executed with the /p modifier.
  In Perl v5.20, the /p modifier does nothing, so ${^MATCH} does the same thing as $MATCH .

test:

echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/g'

output: two empty lines (2x \n)

but the:

echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/gp'

output:

dolor
dolor

My perl:

$ perl -v

This is perl 5, version 24, subversion 0 (v5.24.0) built for darwin-2level
(with 1 registered patch, see perl -V for more detail)

So in the 5.24.0 the /p modifier is still needed? Or what me missed?


问:
Why doesn't DataFrameReader have "avro" method to read avro files?
I see that the DataFrameReader have methods to read parquest, ORC etc. file types but not Avro. What might be the reason?</p>

答: Because parquet and orc are built-in data sources. If you are using Scala, you can use Spark Avro and import com.databricks.spark.avro._, then you will get avro method which is implemented via Scala implicit class.


问:
Have two elements side by side fill all space vertically
I have two elements in my page's body that I want to live side by side and fill all vertical space.

My code is super simple:

```<code><!-- index.html minus all the usual junk-->
<!-- also ignore the lack of a url-tag and the like, it's intentionally left out -->
<body>
  <textarea id="text-field">
  <iframe id="render-field">
</body>
</code>```

and

```<code>// index.css
body {
  font: caption;
  display: flex;
  height: 100%;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}
</code>```

It doesn't matter what I try, the two elements will not fill all the sapce available in the body.

Any help?

答:
First of all, use closing tags.

Second, for height: 100%; you also need to apply that to the html tag to have a height reference for the body element. And also apply margin: 0 to html and body to reset the default margin to zero:

* {
box-sizing: border-box;
}
html {
  height: 100%;
  margin: 0;
}

body {
  font: caption;
  display: flex;
  height: 100%;
  margin: 0;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <textarea id="text-field"></textarea>
  <iframe id="render-field"><iframe>
</body></code>```

Body:
I have two elements in my page's body that I want to live side by side and fill all vertical space.

My code is super simple:

  <textarea id="text-field">

and

// index.css
body {
  font: caption;
  display: flex;
  height: 100%;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}

It doesn't matter what I try, the two elements will not fill all the sapce available in the body.

Any help?

Body:
First of all, use closing tags.

Second, for height: 100%; you also need to apply that to the html tag to have a height reference for the body element. And also apply margin: 0 to html and body to reset the default margin to zero:

* {
box-sizing: border-box;
}
html {
  height: 100%;
  margin: 0;
}

body {
  font: caption;
  display: flex;
  height: 100%;
  margin: 0;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}

<body>
  <textarea id="text-field"></textarea>
  <iframe id="render-field"><iframe>
</body>


问:
Edit with IDLE disappeared for .py files
I used to have the Edit with IDLE option when I right-clicked on .py files but I uninstalled/reinstalled multiple times to get some stuff working and now it's gone. I checked the registry under HKEY_CLASSES_ROOT and HKEY_LOCAL_MACHINE for value under Python.File and Python.NoConFile and it is "C:\Python27\pythonw.exe" "C:\Python27\Lib\idlelib\idle.pyw" -e "%1" so I am not sure why it isn't working. It works for .pyw files though. Can someone help me get this working again? I've also tried repairing my python installation to no avail and following Python IDLE disappeared from the right click context menu.

答:
I have been using python 3.6, and ran into this issue after installing (and later removing) python 2.7
(Thankfully i had another machine with a clean install)

To restore "Edit with IDLE" / file icons / open option:

Make a .reg file with the following, right-click it, and choose 'merge':

( NOTE: "C:\WINDOWS\py.exe" should be correct, but double check that the .exe is there first)

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.py]
@="Python.File"
"Content Type"="text/plain"

[HKEY_CLASSES_ROOT\Python.File]
@="Python File"

[HKEY_CLASSES_ROOT\Python.File\DefaultIcon]
@="\"C:\\WINDOWS\\py.exe\",1"

[HKEY_CLASSES_ROOT\Python.File\Shell]

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle]
"MUIVerb"="&Edit with IDLE"
"Subcommands"=""

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell]

[HKEY_CLASSES_ROOT\Python.File\Shell\open]

[HKEY_CLASSES_ROOT\Python.File\Shell\open\command]
@="\"C:\\WINDOWS\\py.exe\" \"%L\" %*"

[HKEY_CLASSES_ROOT\.pyw]
@="Python.NoConFile"
"Content Type"="text/plain"

[HKEY_CLASSES_ROOT\Python.NoConFile]
@="Python File (no console)"

[HKEY_CLASSES_ROOT\Python.NoConFile\DefaultIcon]
@="\"C:\\WINDOWS\\py.exe\",1"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle]
"MUIVerb"="&Edit with IDLE"
"Subcommands"=""

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\open]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\open\command]
@="\"C:\\WINDOWS\\pyw.exe\" \"%L\" %*"
</code>```

Adding/Fixing versions to the menu:

Here is an example .reg for IDLE 3.6 32 bit, where the █'s are the path to the install (use double \'s)

for other versions change "Edit with IDLE 3.6 (32-bit)" and edit36-32 to match your version

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell\edit36-32]
"MUIVerb"="Edit with IDLE 3.6 (32-bit)"

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell\edit36-32\command]
@="\"███████████████\\pythonw.exe\" -m idlelib \"%L\" %*"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell\edit36-32]
"MUIVerb"="Edit with IDLE 3.6 (32-bit)"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell\edit36-32\command]
@="\"███████████████\\pythonw.exe\" -m idlelib \"%L\" %*"
</code>```

Body:
I have been using python 3.6, and ran into this issue after installing (and later removing) python 2.7
(Thankfully i had another machine with a clean install)

To restore "Edit with IDLE" / file icons / open option:

Make a .reg file with the following, right-click it, and choose 'merge':

( NOTE: "C:\WINDOWS\py.exe" should be correct, but double check that the .exe is there first)

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.py]
@="Python.File"
"Content Type"="text/plain"

[HKEY_CLASSES_ROOT\Python.File]
@="Python File"

[HKEY_CLASSES_ROOT\Python.File\DefaultIcon]
@="\"C:\\WINDOWS\\py.exe\",1"

[HKEY_CLASSES_ROOT\Python.File\Shell]

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle]
"MUIVerb"="&Edit with IDLE"
"Subcommands"=""

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell]

[HKEY_CLASSES_ROOT\Python.File\Shell\open]

[HKEY_CLASSES_ROOT\Python.File\Shell\open\command]
@="\"C:\\WINDOWS\\py.exe\" \"%L\" %*"

[HKEY_CLASSES_ROOT\.pyw]
@="Python.NoConFile"
"Content Type"="text/plain"

[HKEY_CLASSES_ROOT\Python.NoConFile]
@="Python File (no console)"

[HKEY_CLASSES_ROOT\Python.NoConFile\DefaultIcon]
@="\"C:\\WINDOWS\\py.exe\",1"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle]
"MUIVerb"="&Edit with IDLE"
"Subcommands"=""

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\open]

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\open\command]
@="\"C:\\WINDOWS\\pyw.exe\" \"%L\" %*"

Adding/Fixing versions to the menu:

Here is an example .reg for IDLE 3.6 32 bit, where the █'s are the path to the install (use double \'s)

for other versions change "Edit with IDLE 3.6 (32-bit)" and edit36-32 to match your version

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell\edit36-32]
"MUIVerb"="Edit with IDLE 3.6 (32-bit)"

[HKEY_CLASSES_ROOT\Python.File\Shell\editwithidle\shell\edit36-32\command]
@="\"███████████████\\pythonw.exe\" -m idlelib \"%L\" %*"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell\edit36-32]
"MUIVerb"="Edit with IDLE 3.6 (32-bit)"

[HKEY_CLASSES_ROOT\Python.NoConFile\Shell\editwithidle\shell\edit36-32\command]
@="\"███████████████\\pythonw.exe\" -m idlelib \"%L\" %*"


问:
Validation failed: Model1 model2 must exist
I'm attempting to create a has_one/belongs_to relationship through a nested form for the models Survey and UserPair. However, on save!, it throws the error, Validation failed: User pair survey must exist.

The parameters output in the console upon submit are all right, but the survey_id is apparently not getting assigned to survey.user_pair.

parameters output

Parameters: {"utf8"=>"✓", "authenticity_token"=>"bPBK5aTntfnb6WSEv2VchUgETwH1nmGTWDOJJkfniLoKwBSKY1C6xoZ6Z3chQouLb6G8161T/d0AMzn4VXX0Lw==", "survey"=>{"user_pair_attributes"=>{"user1_name"=>"A", "user1_field"=>"def", "user2_name"=>"B", "user2_field"=>"abc"}, "category_ids"=>["", "1", "2"]}, "commit"=>"Start Survey"}

controllers/surveys_controller.rb

```<code>class SurveysController < ApplicationController
  def new
    @survey = Survey.new
    @survey.build_user_pair
  end

  def create
    @survey = Survey.new(survey_params)
    puts @survey.save! // trying to debug validation errors
    if @survey.save
      flash[:success] = "Survey submitted"
      redirect_to @survey
    else
      render 'new'
    end
  end

  private

  def survey_params
    params.require(:survey).permit(category_ids: [], user_pair_attributes: [:user1_name, :user1_field, :user2_name, :user2_field])
  end
end
</code>```

models/survey.rb

```<code>class Survey < ApplicationRecord
  has_secure_token

  has_one :user_pair, dependent: :destroy
  has_many :users, through: :userpair, class_name: 'UserPair'

  accepts_nested_attributes_for :user_pair
end
</code>```

models/user_pair.rb

```<code>class UserPair < ApplicationRecord
  belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
  belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
  belongs_to :survey
end
</code>```

db/migrations/create_surveys.rb

```<code>class CreateSurveys < ActiveRecord::Migration[5.0]
  def change
    create_table :surveys do |t|
      t.string :token
      t.string :category_ids, array: true, default: []
      t.timestamps
    end
  end
end
</code>```

db/migrations/create_user_pairs

```<code>class CreateUserPairs < ActiveRecord::Migration[5.0]
  def change
    create_table :user_pairs do |t|
      # Relationships
      t.belongs_to :user1
      t.belongs_to :user2
      t.belongs_to :survey, foreign_key: true

      # User1 info
      t.string :user1_name
      t.string :user1_field

      # User2 info
      t.string :user2_name
      t.string :user2_field

      t.timestamps
    end
  end
end
</code>```

答:
Try this out:</p>

```<code>class UserPair < ActiveRecord::Base
    belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
    belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
    belongs_to :survey, optional: true
end
</code>```

Body:
I'm attempting to create a has_one/belongs_to relationship through a nested form for the models Survey and UserPair. However, on save!, it throws the error, Validation failed: User pair survey must exist.

The parameters output in the console upon submit are all right, but the survey_id is apparently not getting assigned to survey.user_pair.

parameters output

Parameters: {"utf8"=>"✓", "authenticity_token"=>"bPBK5aTntfnb6WSEv2VchUgETwH1nmGTWDOJJkfniLoKwBSKY1C6xoZ6Z3chQouLb6G8161T/d0AMzn4VXX0Lw==", "survey"=>{"user_pair_attributes"=>{"user1_name"=>"A", "user1_field"=>"def", "user2_name"=>"B", "user2_field"=>"abc"}, "category_ids"=>["", "1", "2"]}, "commit"=>"Start Survey"}

controllers/surveys_controller.rb

class SurveysController < ApplicationController
  def new
    @survey = Survey.new
    @survey.build_user_pair
  end

  def create
    @survey = Survey.new(survey_params)
    puts @survey.save! // trying to debug validation errors
    if @survey.save
      flash[:success] = "Survey submitted"
      redirect_to @survey
    else
      render 'new'
    end
  end

  private

  def survey_params
    params.require(:survey).permit(category_ids: [], user_pair_attributes: [:user1_name, :user1_field, :user2_name, :user2_field])
  end
end

models/survey.rb

class Survey < ApplicationRecord
  has_secure_token

  has_one :user_pair, dependent: :destroy
  has_many :users, through: :userpair, class_name: 'UserPair'

  accepts_nested_attributes_for :user_pair
end

models/user_pair.rb

class UserPair < ApplicationRecord
  belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
  belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
  belongs_to :survey
end

db/migrations/create_surveys.rb

class CreateSurveys < ActiveRecord::Migration[5.0]
  def change
    create_table :surveys do |t|
      t.string :token
      t.string :category_ids, array: true, default: []
      t.timestamps
    end
  end
end

db/migrations/create_user_pairs

class CreateUserPairs < ActiveRecord::Migration[5.0]
  def change
    create_table :user_pairs do |t|
      # Relationships
      t.belongs_to :user1
      t.belongs_to :user2
      t.belongs_to :survey, foreign_key: true

      # User1 info
      t.string :user1_name
      t.string :user1_field

      # User2 info
      t.string :user2_name
      t.string :user2_field

      t.timestamps
    end
  end
end

Body:
Try this out:

class UserPair < ActiveRecord::Base
    belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
    belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
    belongs_to :survey, optional: true
end


问:
Execute Python threads in small groups
I am trying to insert some number(100) of data sets into SQL server using python. I am using multi-threading to create 100 threads in a loop. All of them are starting at the same time and this is bogging down the database. I want to group my threads into set of 5 and once that group is done, I would like to start the next group of threads and so on. As I am new to python and multi-threading, any help would be highly appreciated.Please find my code below.</p>

```<code>for row in datasets:
        argument1=row[0]
        argument2=row[1]
        jobs=[]
        t = Thread(target=insertDataIntoSQLServer, args=(argument1,argument2,))
        jobs.append(t)
        t.start()
for t in jobs:
    t.join()
</code>```

答:
You can create a ThreadPoolExecutor and specify max_workers=5.

See here.

And you can use functools.partial to turn your functions into the required 0-argument functions.

EDIT: You can pass the args in with the function name when you submit to the executor. Thanks, Roland Smith, for reminding me that partial is a bad idea. There was a better way.

Title: Execute Python threads in small groups

Body:
I am trying to insert some number(100) of data sets into SQL server using python. I am using multi-threading to create 100 threads in a loop. All of them are starting at the same time and this is bogging down the database. I want to group my threads into set of 5 and once that group is done, I would like to start the next group of threads and so on. As I am new to python and multi-threading, any help would be highly appreciated.Please find my code below.

for row in datasets:
        argument1=row[0]
        argument2=row[1]
        jobs=[]
        t = Thread(target=insertDataIntoSQLServer, args=(argument1,argument2,))
        jobs.append(t)
        t.start()
for t in jobs:
    t.join()


问:
ANTLR4 doesn't work with custom configuration in Maven
I always used succesfully ANTLR4 combined with Maven inside Eclipse.
I just want to change the default directory where I store my grammar, since I do not like the standard path which is src/main/antlr4. The issue of this path is the creation of a new java package, that I really do not want.
So I simply decided to create another directory inside my project named grammar which contains another directory called imports. I did this following simply the website guidelines.
Despite this, when I change the grammar it doesn't generate automatically the new sources, even with the maven commands!

So, this is my configuration file pom.xml:

```<code><!-- ANTLR4 -->
        <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
                <execution>
                    <configuration>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <libDirectory>grammar/imports</libDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
</code>```

As you can see, the target directory is empty. Before this change, there was a generated-sources directory inside with all the .java files.

So, where is the error?

答:
The correct way is:

```<code><!-- ANTLR4 -->
        <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
                <execution>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <configuration>
                            <libDirectory>grammar/imports</libDirectory>
                        </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

The <configuration> tag must be at same level than <goals> tag, inside <execution> tag, according to Maven documentation: https://maven.apache.org/guides/mini/guide-configuring-plugins.html#Using_the_executions_Tag and https://maven.apache.org/guides/mini/guide-default-execution-ids.html

In fact, the documentation in ANTLR4 Maven plugin is wrong:
http://www.antlr.org/api/maven-plugin/latest/examples/libraries.html

Body:
I always used succesfully ANTLR4 combined with Maven inside Eclipse.
I just want to change the default directory where I store my grammar, since I do not like the standard path which is src/main/antlr4. The issue of this path is the creation of a new java package, that I really do not want.
So I simply decided to create another directory inside my project named grammar which contains another directory called imports. I did this following simply the website guidelines.
Despite this, when I change the grammar it doesn't generate automatically the new sources, even with the maven commands!

So, this is my configuration file pom.xml:

        <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
                <execution>
                    <configuration>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <libDirectory>grammar/imports</libDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>

As you can see, the target directory is empty. Before this change, there was a generated-sources directory inside with all the .java files.

So, where is the error?

Body:
The correct way is:

<!-- ANTLR4 -->
        <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
                <execution>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <configuration>
                            <libDirectory>grammar/imports</libDirectory>
                        </configuration>
                </execution>
            </executions>
        </plugin>

The <configuration> tag must be at same level than <goals> tag, inside <execution> tag, according to Maven documentation: https://maven.apache.org/guides/mini/guide-configuring-plugins.html#Using_the_executions_Tag and https://maven.apache.org/guides/mini/guide-default-execution-ids.html

In fact, the documentation in ANTLR4 Maven plugin is wrong:
http://www.antlr.org/api/maven-plugin/latest/examples/libraries.html


问:
Hide (not remove) HTML5 video controls
Every question on the subject explain how to remove the controls of an HTML5 video element.

```<code>videoElement.removeAttribute('controls');
</code>```

But browsers, Firefox and Chrome, have a way of just hiding the controls which makes them disappear when cursor is not moving and the video is playing. And makes them appear again if you move the cursor or when video stops playing.

<video controls><source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>```

Video test file: http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4

If you play the above video, and leave it alone without moving the cursor, the controls will disappear. The if you move the cursor again they'll appear again. They'll also appear upon pausing or video finishing.

Very much like popular native or desktop video players.

This is what I want. I want to hide the controls the same way they would automatically hide if the video were playing and the cursor hasn't moved for a while.

Is there a way to achieve this without removing the controls entirely?

答:
I'm using videojs.com library and the solution was to add

```<code>.vjs-control-bar {
    display:none !important;
}
</code>```

to the stylesheet.

Title: Hide (not remove) HTML5 video controls

Body:
Every question on the subject explain how to remove the controls of an HTML5 video element.

videoElement.removeAttribute('controls');

But browsers, Firefox and Chrome, have a way of just hiding the controls which makes them disappear when cursor is not moving and the video is playing. And makes them appear again if you move the cursor or when video stops playing.

<video controls><source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>

Video test file: http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4

If you play the above video, and leave it alone without moving the cursor, the controls will disappear. The if you move the cursor again they'll appear again. They'll also appear upon pausing or video finishing.

Very much like popular native or desktop video players.

This is what I want. I want to hide the controls the same way they would automatically hide if the video were playing and the cursor hasn't moved for a while.

Is there a way to achieve this without removing the controls entirely?

Body:
I'm using videojs.com library and the solution was to add

.vjs-control-bar {
    display:none !important;
}

to the stylesheet.


问:
Xamarin Forms DependencyService with Prism with Autofac crash - Unhandled Exception
So to continue on with my first foray into Xamarin, I'm trying to develop an Content page that will take a photo, and then save the photo on the device gallery for viewing. I'm using Prism with Autofac and I'm following the wiki documentation on DependencyService and the examples that was provided on GitHub, but the program is crashing without explaining why.

I hate that!

So, here's my interface:

```<code>   public interface ISavePicture
{
    void SavePictureToGallery(string path);
}
</code>```

ViewModel:

```<code>public class PluginPageViewModel : BindableBase
{
    private ISavePicture _savePicture;

    public PluginPageViewModel(ISavePicture savePicture)
    {
        try
        {
            TakePicCommand = new DelegateCommand(TakePicture);
            _savePicture = savePicture;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

    }

    public  ICommand TakePicCommand { get; private set; }

    private async void TakePicture()
    {
        try
            // Code here for getting the camera to take a picture ...

            _savePicture.SavePictureToGallery(filePath);
        }

        catch (Exception e)
        {
            Debug.WriteLine(e);
            throw;
        }

    }

  }
}
</code>```

and the Android code:

```<code>using Android.App;
using Android.Content;
using Java.IO;
using RolodexDEMO_XF.Droid.Service;
using RolodexDEMO_XF.Services;
using Xamarin.Forms;
using Uri = Android.Net.Uri;

[assembly: Dependency(typeof(SavePicture_Android))]
namespace RolodexDEMO_XF.Droid.Service
{
    public class SavePicture_Android : Activity, ISavePicture
    {
        public void SavePictureToGallery(string path)
        {
            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            var file = new File(path);
            Uri contentUri = Uri.FromFile(file);
            mediaScanIntent.SetData(contentUri);
            SendBroadcast(mediaScanIntent);
        }
    }
}
</code>```

Notice that I DO have the assembly attribute for the DependencyService. I also wanted to note that I'm not using the emulator to test it out. Instead, I'm using my Galaxy Note 4 since I'm trying to test out the camera. For that part, I'm using Xamarin.Plugins from James Montemagno and that's working fine. I just can't save it, or see the pic if it is indeed saved to the device.

So where am I going wrong with it?

UPDATE: I was asked by others on what permissions I'm putting into my Android app, so in the AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="RolodexDEMOXF.RolodexDEMOXF">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:theme="@style/MyTheme" android:label="Rolodex DEMO">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="RolodexDEMOXF.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>
</manifest>
</code>```

and in the file_paths.xml (in the Resources\xml directory)

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/RolodexDEMOXF/files/Pictures" />
    <external-path name="my_movies" path="Android/data/RolodexDEMOXF/files/Movies" />
</paths>
</code>```

答:
I'm putting in the answer here just in case someone else has the same problem as I do in the future. Also, since there's little documentation, and I had to cobble together this alternative solution from a Chinese website (of all places!) and discussion with some of the guys on Slate Prism-Forms channel, I thought it would be best to put it out there on the alternative solution so at least you get an rudimentary idea on to resolve the DependencyService issues, and workarounds using Autofac DI.

I do want to note that there is discussion going on the Prism GitHub that Prism's implementation of DependencyService should be depreciated and go through this alternative that I'm describing here in this post. So hopefully one of the guys on the development team will document it and give better code examples on what I'm showing here.

That said, on with the show...

Okay, so I found out the answer to the problem. Long story short, the problem is the Autofac container.

And now the long winded version.

From what I gathered Dan Siegel, of all the containers that Prism can implement for a IoC/DI container, I had to pick the one that doesn't play well with others!

Why, do I say that it doesn't play well? According to the Autofac documentation, the container is Immutable which means it cannot be modified once it's been built. So my hypothesis is that when Prism goes through the project and tries to add in the registration types of DependencyService, Autofac is balking because the container is already built and therefore the "Unhandled Exception" is being thrown.

That explains the issue, but not the solution.

And what is the solution? Well, it turns out that Brian (Lagunas) and Brian (Noyes) have implemented a new interface called IPlatformInitializer, and I therefore have no choice but to use ContainerBuilder.Update(container) to add in the new RegisterType, which implements the additional RegisterTypes for the DependencyService, and I had to implement it like this:

```<code>public class AndroidInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainer container)
    {
        var temp = new ContainerBuilder();

        temp.RegisterType<SavePicture_Android>().As<ISavePicture>();
        temp.RegisterType<MessageService_Android>().As<IMessageService>();
        // ... add more RegisterTypes as needed ...

        temp.Update(container);
    }
}
</code>```

This class is already included in the Prism template project. For Android, it's in MainActivity.cs file.

Just in case you're wondering, it's the same for iOS and UWP. So instead of being AndroidInitializer:

iOSInitializer : IPlatformInitializer (iOS) (inside AppDelegate.cs)

UWPInitializer : IPlatformInitializer (UWP) (inside MainPage.xaml.cs)

On last thing: You can dump the [Assembly Dependency(typeof(X))] attribute since it is no longer needed. But you still need to do constructor dependency injection as they stated in their documentation for DependencyService.

As I said, the Prism gang is kicking around the idea of getting rid of their implementation of DependencyService on the next build of Prism and go down this route that I've explained to  you.

It's also interesting to note is that the guys over Autofac are ALSO discussing on getting rid of the ContainerBuilder.Update() on the next version release of Autofac 4.

Just some fair warning, because of what I've put here may go out the window in the future.

I hope it helps someone out!

Body:
So to continue on with my first foray into Xamarin, I'm trying to develop an Content page that will take a photo, and then save the photo on the device gallery for viewing. I'm using Prism with Autofac and I'm following the wiki documentation on DependencyService and the examples that was provided on GitHub, but the program is crashing without explaining why.

I hate that!

So, here's my interface:

   public interface ISavePicture
{
    void SavePictureToGallery(string path);
}

ViewModel:

public class PluginPageViewModel : BindableBase
{
    private ISavePicture _savePicture;

    public PluginPageViewModel(ISavePicture savePicture)
    {
        try
        {
            TakePicCommand = new DelegateCommand(TakePicture);
            _savePicture = savePicture;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

    }

    public  ICommand TakePicCommand { get; private set; }

    private async void TakePicture()
    {
        try
            // Code here for getting the camera to take a picture ...

            _savePicture.SavePictureToGallery(filePath);
        }

        catch (Exception e)
        {
            Debug.WriteLine(e);
            throw;
        }

    }

  }
}

and the Android code:

using Android.App;
using Android.Content;
using Java.IO;
using RolodexDEMO_XF.Droid.Service;
using RolodexDEMO_XF.Services;
using Xamarin.Forms;
using Uri = Android.Net.Uri;

[assembly: Dependency(typeof(SavePicture_Android))]
namespace RolodexDEMO_XF.Droid.Service
{
    public class SavePicture_Android : Activity, ISavePicture
    {
        public void SavePictureToGallery(string path)
        {
            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            var file = new File(path);
            Uri contentUri = Uri.FromFile(file);
            mediaScanIntent.SetData(contentUri);
            SendBroadcast(mediaScanIntent);
        }
    }
}

Notice that I DO have the assembly attribute for the DependencyService. I also wanted to note that I'm not using the emulator to test it out. Instead, I'm using my Galaxy Note 4 since I'm trying to test out the camera. For that part, I'm using Xamarin.Plugins from James Montemagno and that's working fine. I just can't save it, or see the pic if it is indeed saved to the device.

So where am I going wrong with it?

UPDATE: I was asked by others on what permissions I'm putting into my Android app, so in the AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="RolodexDEMOXF.RolodexDEMOXF">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:theme="@style/MyTheme" android:label="Rolodex DEMO">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="RolodexDEMOXF.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>
</manifest>

and in the file_paths.xml (in the Resources\xml directory)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/RolodexDEMOXF/files/Pictures" />
    <external-path name="my_movies" path="Android/data/RolodexDEMOXF/files/Movies" />
</paths>

Body:
I'm putting in the answer here just in case someone else has the same problem as I do in the future. Also, since there's little documentation, and I had to cobble together this alternative solution from a Chinese website (of all places!) and discussion with some of the guys on Slate Prism-Forms channel, I thought it would be best to put it out there on the alternative solution so at least you get an rudimentary idea on to resolve the DependencyService issues, and workarounds using Autofac DI.

I do want to note that there is discussion going on the Prism GitHub that Prism's implementation of DependencyService should be depreciated and go through this alternative that I'm describing here in this post. So hopefully one of the guys on the development team will document it and give better code examples on what I'm showing here.

That said, on with the show...

Okay, so I found out the answer to the problem. Long story short, the problem is the Autofac container.

And now the long winded version.

From what I gathered Dan Siegel, of all the containers that Prism can implement for a IoC/DI container, I had to pick the one that doesn't play well with others!

Why, do I say that it doesn't play well? According to the Autofac documentation, the container is Immutable which means it cannot be modified once it's been built. So my hypothesis is that when Prism goes through the project and tries to add in the registration types of DependencyService, Autofac is balking because the container is already built and therefore the "Unhandled Exception" is being thrown.

That explains the issue, but not the solution.

And what is the solution? Well, it turns out that Brian (Lagunas) and Brian (Noyes) have implemented a new interface called IPlatformInitializer, and I therefore have no choice but to use ContainerBuilder.Update(container) to add in the new RegisterType, which implements the additional RegisterTypes for the DependencyService, and I had to implement it like this:

public class AndroidInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainer container)
    {
        var temp = new ContainerBuilder();

        temp.RegisterType<SavePicture_Android>().As<ISavePicture>();
        temp.RegisterType<MessageService_Android>().As<IMessageService>();
        // ... add more RegisterTypes as needed ...

        temp.Update(container);
    }
}

This class is already included in the Prism template project. For Android, it's in MainActivity.cs file.

Just in case you're wondering, it's the same for iOS and UWP. So instead of being AndroidInitializer:

iOSInitializer : IPlatformInitializer (iOS) (inside AppDelegate.cs)

UWPInitializer : IPlatformInitializer (UWP) (inside MainPage.xaml.cs)

On last thing: You can dump the [Assembly Dependency(typeof(X))] attribute since it is no longer needed. But you still need to do constructor dependency injection as they stated in their documentation for DependencyService.

As I said, the Prism gang is kicking around the idea of getting rid of their implementation of DependencyService on the next build of Prism and go down this route that I've explained to  you.

It's also interesting to note is that the guys over Autofac are ALSO discussing on getting rid of the ContainerBuilder.Update() on the next version release of Autofac 4.

Just some fair warning, because of what I've put here may go out the window in the future.

I hope it helps someone out!


问:
How to find the MAC address of a 'shutdown' system on local lan (is it possible?)
How to find out the mac address of a system which is:

Shutdown

Power plugged in

Connected to Lan

Nic card ON.

Update
I am asking how to find out the mac address of some other system which is already shutdown.... and which is on lan..

I want to find out its mac from my system.... and to be clear... I want to tell that.. arp table can be populated by using ping .. i.e. if 172.16.3.12 is not in arp table then it can be added by just ping 172.16.3.12 but a system can be pinged only if its on ... a shutdown system can't be pinged...

答:
try to use getmac command

example: getmac /s [IP address]
but i cannot know the mac address of computer turned off by this command


问:
PHP Logic Assistance (Selecting Highest Value in Array / Randomly choosing if they match)
I'm creating a Statistical Based 'AI' system for Rock, Paper, Scissors that uses a DB to store what Players most commonly throw next after a specific pattern of throws. They are stored in the database in the way displayed below.

```<code>ThrowHistory - [[Player Throws],[AI Throws]] (JSON Encoded Array) | Rock | Paper | Scissors
[["Paper","Scissors","Paper"],["Rock","Paper","Rock"]]            |     4|      3|        4
</code>```

Using the information displayed in the DB (as shown above), I need to get the highest value of the Rock, Paper, Scissor fields and return the field name (to show the most common throw). If, like in the example above, the highest value is in two/three fields it needs to choose randomly between them, so in this case it must randomly choose between Rock and Scissors.

The code I currently use is:

```<code>    $StrQuery = "SELECT Rock, Paper, Scissors FROM tblThrows WHERE ThrowHistory = ?";
    $StrThrowHistory = json_encode($_SESSION["ThrowHistory"]);
    if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
        $statement->bind_param('s', $StrThrowHistory);
        $statement->execute();
        $results = $statement->get_result();
        $row = $results->fetch_assoc();

        $LstThrowNumbers = array("Rock" => $row["Rock"], "Paper" => $row["Paper"], "Scissors" => $row["Scissors"]);
    }

    if(count(array_unique($LstThrowNumbers)) != 1){
        return array_search(max($LstThrowNumbers), $LstThrowNumbers);
    }
    else{
        $LstOutcomes = array("Rock", "Paper", "Scissors");
        $IntPredictedThrow = rand(0, 2);
        return $LstOutcomes[$IntPredictedThrow];
    }
</code>```

However, this code does not seem to work (no error just skips to the else) and even if it did it is not a perfect solution as it would randomly pick between all 3 options rather than the two highest values. So I need to figure out a new solution, however that's where I'm out of simple ideas. Any suggestions? Thanks.

答:
You can create a new array ordered by number of times a moved has appeared, and use shuffle to randomize the order in case of multiple highest matches:

```<code>//in your case, $row is returned from sql
$row = [
    'rock'=>4,
    'paper'=>3,
    'scissors'=>4
];

//array to hold values index by number of times move has appeared
$temp=[];

foreach($row as $k=>$v)
    $temp[$v][]=$k;

//sort the array, the last element now holds the highest move(s);
ksort($temp);

//get the last element, this is an array with 1,2 or 3 elements
$highest = array_pop($temp);

//shuffle the array, randomizing the order
shuffle($highest);
//grap the last elements in the shuffled array
$chosen = array_pop($highest);

var_dump($chosen); //will randomly show rock or scissors
</code>```

Body:
I'm creating a Statistical Based 'AI' system for Rock, Paper, Scissors that uses a DB to store what Players most commonly throw next after a specific pattern of throws. They are stored in the database in the way displayed below.

ThrowHistory - [[Player Throws],[AI Throws]] (JSON Encoded Array) | Rock | Paper | Scissors
[["Paper","Scissors","Paper"],["Rock","Paper","Rock"]]            |     4|      3|        4

Using the information displayed in the DB (as shown above), I need to get the highest value of the Rock, Paper, Scissor fields and return the field name (to show the most common throw). If, like in the example above, the highest value is in two/three fields it needs to choose randomly between them, so in this case it must randomly choose between Rock and Scissors.

The code I currently use is:

    $StrQuery = "SELECT Rock, Paper, Scissors FROM tblThrows WHERE ThrowHistory = ?";
    $StrThrowHistory = json_encode($_SESSION["ThrowHistory"]);
    if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
        $statement->bind_param('s', $StrThrowHistory);
        $statement->execute();
        $results = $statement->get_result();
        $row = $results->fetch_assoc();

        $LstThrowNumbers = array("Rock" => $row["Rock"], "Paper" => $row["Paper"], "Scissors" => $row["Scissors"]);
    }

    if(count(array_unique($LstThrowNumbers)) != 1){
        return array_search(max($LstThrowNumbers), $LstThrowNumbers);
    }
    else{
        $LstOutcomes = array("Rock", "Paper", "Scissors");
        $IntPredictedThrow = rand(0, 2);
        return $LstOutcomes[$IntPredictedThrow];
    }

However, this code does not seem to work (no error just skips to the else) and even if it did it is not a perfect solution as it would randomly pick between all 3 options rather than the two highest values. So I need to figure out a new solution, however that's where I'm out of simple ideas. Any suggestions? Thanks.

Body:
You can create a new array ordered by number of times a moved has appeared, and use shuffle to randomize the order in case of multiple highest matches:

//in your case, $row is returned from sql
$row = [
    'rock'=>4,
    'paper'=>3,
    'scissors'=>4
];

//array to hold values index by number of times move has appeared
$temp=[];

foreach($row as $k=>$v)
    $temp[$v][]=$k;

//sort the array, the last element now holds the highest move(s);
ksort($temp);

//get the last element, this is an array with 1,2 or 3 elements
$highest = array_pop($temp);

//shuffle the array, randomizing the order
shuffle($highest);
//grap the last elements in the shuffled array
$chosen = array_pop($highest);

var_dump($chosen); //will randomly show rock or scissors


问:
Cassandra back using java code
Is there a way that i can backup a single table in Apache Cassandra with java code. i want to run such code once every week using a scheduler. Can some one share links to such resources, if there any?</p>

答:
Have a look at this answer.

Fetch all rows in cassandra

It's just a matter of adding code to export let's say every row to csv or some similar format that would be fine for you.

You will also have to write script to load this data, but those are just simple inserts.

Title: Cassandra back using java code