问:
Rails - How to do If and else statements in a text field
I am trying to do a if and else statement in this text field with the value:

```<code><%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>
</code>```

I get this error in view:

```<code>SyntaxError in Kategoris#show

Showing C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb where line #3 raised:

C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_then or ';' or '\n'
...ue => if vind.ratings == 0 else vind.rating_score/vind.ratin...
...                               ^
C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected ',', expecting ')'
...vind.rating_score/vind.ratings, :type => 'range', :step => '...
...                               ^
</code>```

答:
```<code><%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>
</code>```

Which ends up looking like this for :value.

```<code> :value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings
</code>```

Body:
I am trying to do a if and else statement in this text field with the value:

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>

I get this error in view:

SyntaxError in Kategoris#show

Showing C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb where line #3 raised:

C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_then or ';' or '\n'
...ue => if vind.ratings == 0 else vind.rating_score/vind.ratin...
...                               ^
C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected ',', expecting ')'
...vind.rating_score/vind.ratings, :type => 'range', :step => '...
...                               ^

Body:
<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>

Which ends up looking like this for :value.

 :value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings


来源: stackexchange

问:
DataGridView Changing AutoSizeRowsMode Throws Exception
If a dgv is currently has AutoSizeRowsMode = DisplayedCells, then setting to None causes an exception.

Below is the code to reproduce the issue. To cause the exception to occur, simply click on one of the column headers. The exception will happen even if some of the rows are visible. However, if the Form is resized large enough then the exception stops happening. Tested using .NET35 .NET40 and .NET45.

```<code>public class MyForm : Form {
    Button btn = new Button { Text = "Button" };

    public MyForm() {
        Controls.Add(btn);
        btn.Click += btn_Click;
    }

    void btn_Click(object sender, EventArgs e) {
        DataGridView dgv = new DataGridView { Dock = DockStyle.Fill };
        dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
        dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; // <---- this is required to cause the exception
        dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font(SystemFonts.MenuFont.FontFamily, 14f, FontStyle.Bold);

        // The underlying data source doesn't matter, exception happens in both cases
        //dgv.Columns.Add("Column1", "Column1");
        //dgv.Columns.Add("Column2", "Column2");
        //dgv.Columns.Add("Column3", "Column3");

        DataTable table = new DataTable();
        table.Columns.Add("Column1");
        table.Columns.Add("Column2");
        table.Columns.Add("Column3");
        for (int i = 0; i < 10; i++) {
            table.Rows.Add(i, i, i);
            //dgv.Rows.Add(i, i, i);
        }
        dgv.DataSource = table;
        Form f = new Form();
        f.Controls.Add(dgv);
        f.Size = new System.Drawing.Size(400, 90); // just enough so only the headers are visible
        f.Show();

        dgv.MouseDown += dgv_MouseDown;
    }

    void dgv_MouseDown(object sender, MouseEventArgs e) {
        DataGridView dgv = (DataGridView) sender;

        // using reflection, the Exception occurs on rowIndex == 1
        //int index = 0;
        //Type ty = typeof(DataGridViewRow);
        //var pi = ty.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).Cast<PropertyInfo>().Where(p => p.Name == "ThicknessInternal").FirstOrDefault();
        //var pi2 = ty.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).Cast<PropertyInfo>().Where(p => p.Name == "CachedThickness").FirstOrDefault();
        //for (index = dgv.Rows.GetFirstRow(DataGridViewElementStates.Visible); index != -1; index =  dgv.Rows.GetNextRow(index, DataGridViewElementStates.Visible)) {
        //  DataGridViewRow dataGridViewRow = dgv.Rows.SharedRow(index);
        //  object val1 = pi.GetValue(dataGridViewRow);
        //  object val2 = pi.GetValue(dataGridViewRow);
        //  pi.SetValue(dataGridViewRow, val2);
        //}

        dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; // <------- Exception here
    }

}
</code>```

Here is the exception stack trace:

```<code>   at System.Windows.Forms.DataGridViewRowCollection.GetRowState(Int32 rowIndex)
   at System.Windows.Forms.DataGridView.OnRowGlobalAutoSize(Int32 rowIndex)
   at System.Windows.Forms.DataGridView.RestoreRowsCachedThickness()
   at System.Windows.Forms.DataGridView.OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventArgs e)
   at Program.MyForm.dgv_MouseDown(Object sender, MouseEventArgs e) in c:\temp\...\Program.cs:line 2483
</code>```

Looking at the source code for DataGridView on MSDN: http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridViewMethods.cs,237455f3980aebd9

The RestoreRowsCachedThickness loops through each row and sets: dataGridViewRow.ThicknessInternal = dataGridViewRow.CachedThickness;

The DataGridViewBand.ThicknessInternal property doesn't check to see if the values are actually different, it always fires the OnBandThicknessChanged event.

That triggers an event which calls a couple of other methods, eventually getting to the line:

```<code>    private void OnRowGlobalAutoSize(int rowIndex)
    {
        DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex);
//...
    }
</code>```

It is strange that the RowCollection is throwing an index out of bounds exception.

Is there a sensible way to handle this exception (bug?) besides wrapping it in a try-catch statement?

答:
Call LoopThroughRows(dgv) before setting the AutoSizeRowsMode property. The DataGridView doesn't create rows if it doesn't has to. Looping through the rows forces the creation of each row and prevents the exception.

Possibly in Release mode the code might be removed by the optimizer, hence the attributes.

```<code>[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoOptimization | System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void LoopThroughRows(DataGridView dgv) {
    DataGridViewRowCollection rows = dgv.Rows;
    for (int i = rows.Count - 1; i >= 0; i--) {
        DataGridViewRow row = rows[i];
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If a dgv is currently has AutoSizeRowsMode = DisplayedCells, then setting to None causes an exception.

Below is the code to reproduce the issue. To cause the exception to occur, simply click on one of the column headers. The exception will happen even if some of the rows are visible. However, if the Form is resized large enough then the exception stops happening. Tested using .NET35 .NET40 and .NET45.

public class MyForm : Form {
    Button btn = new Button { Text = "Button" };

    public MyForm() {
        Controls.Add(btn);
        btn.Click += btn_Click;
    }

    void btn_Click(object sender, EventArgs e) {
        DataGridView dgv = new DataGridView { Dock = DockStyle.Fill };
        dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
        dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; // <---- this is required to cause the exception
        dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font(SystemFonts.MenuFont.FontFamily, 14f, FontStyle.Bold);

        // The underlying data source doesn't matter, exception happens in both cases
        //dgv.Columns.Add("Column1", "Column1");
        //dgv.Columns.Add("Column2", "Column2");
        //dgv.Columns.Add("Column3", "Column3");

        DataTable table = new DataTable();
        table.Columns.Add("Column1");
        table.Columns.Add("Column2");
        table.Columns.Add("Column3");
        for (int i = 0; i < 10; i++) {
            table.Rows.Add(i, i, i);
            //dgv.Rows.Add(i, i, i);
        }
        dgv.DataSource = table;
        Form f = new Form();
        f.Controls.Add(dgv);
        f.Size = new System.Drawing.Size(400, 90); // just enough so only the headers are visible
        f.Show();

        dgv.MouseDown += dgv_MouseDown;
    }

    void dgv_MouseDown(object sender, MouseEventArgs e) {
        DataGridView dgv = (DataGridView) sender;

        // using reflection, the Exception occurs on rowIndex == 1
        //int index = 0;
        //Type ty = typeof(DataGridViewRow);
        //var pi = ty.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).Cast<PropertyInfo>().Where(p => p.Name == "ThicknessInternal").FirstOrDefault();
        //var pi2 = ty.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).Cast<PropertyInfo>().Where(p => p.Name == "CachedThickness").FirstOrDefault();
        //for (index = dgv.Rows.GetFirstRow(DataGridViewElementStates.Visible); index != -1; index =  dgv.Rows.GetNextRow(index, DataGridViewElementStates.Visible)) {
        //  DataGridViewRow dataGridViewRow = dgv.Rows.SharedRow(index);
        //  object val1 = pi.GetValue(dataGridViewRow);
        //  object val2 = pi.GetValue(dataGridViewRow);
        //  pi.SetValue(dataGridViewRow, val2);
        //}

        dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; // <------- Exception here
    }

}

Here is the exception stack trace:

   at System.Windows.Forms.DataGridViewRowCollection.GetRowState(Int32 rowIndex)
   at System.Windows.Forms.DataGridView.OnRowGlobalAutoSize(Int32 rowIndex)
   at System.Windows.Forms.DataGridView.RestoreRowsCachedThickness()
   at System.Windows.Forms.DataGridView.OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventArgs e)
   at Program.MyForm.dgv_MouseDown(Object sender, MouseEventArgs e) in c:\temp\...\Program.cs:line 2483

Looking at the source code for DataGridView on MSDN: http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridViewMethods.cs,237455f3980aebd9

The RestoreRowsCachedThickness loops through each row and sets: dataGridViewRow.ThicknessInternal = dataGridViewRow.CachedThickness;

The DataGridViewBand.ThicknessInternal property doesn't check to see if the values are actually different, it always fires the OnBandThicknessChanged event.

That triggers an event which calls a couple of other methods, eventually getting to the line:

    private void OnRowGlobalAutoSize(int rowIndex)
    {
        DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex);
//...
    }

It is strange that the RowCollection is throwing an index out of bounds exception.

Is there a sensible way to handle this exception (bug?) besides wrapping it in a try-catch statement?

Body:
Call LoopThroughRows(dgv) before setting the AutoSizeRowsMode property. The DataGridView doesn't create rows if it doesn't has to. Looping through the rows forces the creation of each row and prevents the exception.

Possibly in Release mode the code might be removed by the optimizer, hence the attributes.

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoOptimization | System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void LoopThroughRows(DataGridView dgv) {
    DataGridViewRowCollection rows = dgv.Rows;
    for (int i = rows.Count - 1; i >= 0; i--) {
        DataGridViewRow row = rows[i];
    }
}

ContentLicense: CC BY-SA 4.0


问:
pandas reading keys as values from a list of dictionaries by default
For some weird reason pandas DataFrame function does not seem to work as expected when providing it a proper list of dictionaries. Instead of reading the key as column name and the values as actual rows, it reads the key names as values for each row.

I've already tried several variations using .from_records and .from_dict without any result. Full code:

```<code>In [44]:
from zeep import Client
import pandas as pd
client = Client('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl')

results = []
requests = [['IE', '6390845P'],['NL', '6390845P']]

for x in requests:
    results.append(client.service.checkVat(x[0],x[1]))

results

Out[44]:
[{
     'countryCode': 'IE',
     'vatNumber': '6390845P',
     'requestDate': datetime.date(2019, 5, 29),
     'valid': True,
     'name': 'BLACKNIGHT INTERNET SOLUTIONS LTD',
     'address': 'UNIT 12A, BARROWSIDE BUSINESS PARK, SLEATY ROAD, GRAIGUECULLEN CARLOW'
 }, {
     'countryCode': 'NL',
     'vatNumber': '6390845P',
     'requestDate': datetime.date(2019, 5, 29),
     'valid': False,
     'name': '---',
     'address': '---'
 }]

In [68]:

df = pd.DataFrame(results)
df

</code>```

Resulting in

```<code>+---+-------------+-----------+-------------+-------+------+---------+
|   | 0           | 1         | 2           | 3     | 4    | 5       |
+---+-------------+-----------+-------------+-------+------+---------+
| 0 | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+
| 1 | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+
</code>```

Needs to be

```<code>+---+-------------+-----------+-------------+-------+------+---------+
|   | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+
| 0 | IE          | 6390845P  | 2019/5/29   | true  | etc. | etc.    |
+---+-------------+-----------+-------------+-------+------+---------+
| 1 | NL          | 6390845P  | 2019/5/29   | false | ---  | ---     |
+---+-------------+-----------+-------------+-------+------+---------+
</code>```

答:
I think what you're trying to do is a little bit wrong, the constructor of DataFrame doesn't take as argument whatever array you want, it can receive

ndarray (structured or homogeneous), Iterable, dict, or DataFrame

So if you want to use a dictionary this is the correct way to use it:

```<code>>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
   col1  col2
0     1     3
1     2     4
</code>```

This is the example provided by doc.

I think you should specify in your dictionary first a column (e.g. 'col1') and then an array containing values, so your dicionary seems not to be well formed:
Your result should be something like:

```<code>{
'countryCode' : ['IE','NL'],
'vatNumber':[6390845P,6390845P],
'requestDate': [datetime.date(2019, 5, 29),datetime.date(2019, 5, 29)],
'valid':[True, False],
'name': ['BLACKNIGHT INTERNET SOLUTIONS LTD', '---'],
'address': ['UNIT 12A, BARROWSIDE BUSINESS PARK, SLEATY ROAD, GRAIGUECULLEN CARLOW', '---']
}
</code>```

Or you can use different functions like others have suggested! I hope this helps

Body:
For some weird reason pandas DataFrame function does not seem to work as expected when providing it a proper list of dictionaries. Instead of reading the key as column name and the values as actual rows, it reads the key names as values for each row.

I've already tried several variations using .from_records and .from_dict without any result. Full code:

In [44]:
from zeep import Client
import pandas as pd
client = Client('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl')

results = []
requests = [['IE', '6390845P'],['NL', '6390845P']]

for x in requests:
    results.append(client.service.checkVat(x[0],x[1]))

results

Out[44]:
[{
     'countryCode': 'IE',
     'vatNumber': '6390845P',
     'requestDate': datetime.date(2019, 5, 29),
     'valid': True,
     'name': 'BLACKNIGHT INTERNET SOLUTIONS LTD',
     'address': 'UNIT 12A, BARROWSIDE BUSINESS PARK, SLEATY ROAD, GRAIGUECULLEN CARLOW'
 }, {
     'countryCode': 'NL',
     'vatNumber': '6390845P',
     'requestDate': datetime.date(2019, 5, 29),
     'valid': False,
     'name': '---',
     'address': '---'
 }]

In [68]:

df = pd.DataFrame(results)
df

Resulting in

+---+-------------+-----------+-------------+-------+------+---------+
|   | 0           | 1         | 2           | 3     | 4    | 5       |
+---+-------------+-----------+-------------+-------+------+---------+
| 0 | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+
| 1 | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+

Needs to be

+---+-------------+-----------+-------------+-------+------+---------+
|   | countryCode | vatNumber | requestDate | valid | name | address |
+---+-------------+-----------+-------------+-------+------+---------+
| 0 | IE          | 6390845P  | 2019/5/29   | true  | etc. | etc.    |
+---+-------------+-----------+-------------+-------+------+---------+
| 1 | NL          | 6390845P  | 2019/5/29   | false | ---  | ---     |
+---+-------------+-----------+-------------+-------+------+---------+

Body:
I think what you're trying to do is a little bit wrong, the constructor of DataFrame doesn't take as argument whatever array you want, it can receive

ndarray (structured or homogeneous), Iterable, dict, or DataFrame

So if you want to use a dictionary this is the correct way to use it:

>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
   col1  col2
0     1     3
1     2     4

This is the example provided by doc.

I think you should specify in your dictionary first a column (e.g. 'col1') and then an array containing values, so your dicionary seems not to be well formed:
Your result should be something like:

{
'countryCode' : ['IE','NL'],
'vatNumber':[6390845P,6390845P],
'requestDate': [datetime.date(2019, 5, 29),datetime.date(2019, 5, 29)],
'valid':[True, False],
'name': ['BLACKNIGHT INTERNET SOLUTIONS LTD', '---'],
'address': ['UNIT 12A, BARROWSIDE BUSINESS PARK, SLEATY ROAD, GRAIGUECULLEN CARLOW', '---']
}

Or you can use different functions like others have suggested! I hope this helps


问:
Delete all users from firebase auth console
Is there an easy way to delete all registered users from firebase console?
For example, I created a hundred users from my development environment, and now I want to delete all of them.</p>

答:
Fully working solution using Firebase Admin SDK

Using the Firebase Admin SDK is really easy and the recommended way to perform such tasks on your Firebase data. This solution is unlike the other makeshift solutions using the developer console.

I just put together a Node.js script to delete all users in your Firebase authentication. I have already tested it by deleting ~10000 users. I simply ran the following Node.js code.

To setup Firebase Admin SDK

Create a new folder. Run the following in terminal

```<code>npm init
sudo npm install firebase-admin --save
</code>```

Now create an index.js file in this folder.

Steps to follow:

Go to your Firebase project -> Project Settings -> Service Accounts.

Click on Generate new Private Key to download the JSON file. Copy the path to JSON file and replace it in the code below in the path to service accounts private key json file.

Also, copy the databaseURL from the settings page. Replace it in the code.

Copy and paste the code in index.js.

Run in terminal node index.js. Watch the mayhem!

```<code>var admin = require('firebase-admin');

var serviceAccount = require("/path/to/service/accounts/private/key/json/file");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "/url/to/your/database"
});

function deleteUser(uid) {
    admin.auth().deleteUser(uid)
        .then(function() {
            console.log('Successfully deleted user', uid);
        })
        .catch(function(error) {
            console.log('Error deleting user:', error);
        });
}

function getAllUsers(nextPageToken) {
    admin.auth().listUsers(100, nextPageToken)
        .then(function(listUsersResult) {
            listUsersResult.users.forEach(function(userRecord) {
                uid = userRecord.toJSON().uid;
                deleteUser(uid);
            });
            if (listUsersResult.pageToken) {
                getAllUsers(listUsersResult.pageToken);
            }
        })
        .catch(function(error) {
            console.log('Error listing users:', error);
        });
}

getAllUsers();
</code>```

Body:
Fully working solution using Firebase Admin SDK

Using the Firebase Admin SDK is really easy and the recommended way to perform such tasks on your Firebase data. This solution is unlike the other makeshift solutions using the developer console.

I just put together a Node.js script to delete all users in your Firebase authentication. I have already tested it by deleting ~10000 users. I simply ran the following Node.js code.

To setup Firebase Admin SDK

Create a new folder. Run the following in terminal

npm init
sudo npm install firebase-admin --save

Now create an index.js file in this folder.

Steps to follow:

Go to your Firebase project -> Project Settings -> Service Accounts.

Click on Generate new Private Key to download the JSON file. Copy the path to JSON file and replace it in the code below in the path to service accounts private key json file.

Also, copy the databaseURL from the settings page. Replace it in the code.

Copy and paste the code in index.js.

Run in terminal node index.js. Watch the mayhem!

var admin = require('firebase-admin');

var serviceAccount = require("/path/to/service/accounts/private/key/json/file");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "/url/to/your/database"
});

function deleteUser(uid) {
    admin.auth().deleteUser(uid)
        .then(function() {
            console.log('Successfully deleted user', uid);
        })
        .catch(function(error) {
            console.log('Error deleting user:', error);
        });
}

function getAllUsers(nextPageToken) {
    admin.auth().listUsers(100, nextPageToken)
        .then(function(listUsersResult) {
            listUsersResult.users.forEach(function(userRecord) {
                uid = userRecord.toJSON().uid;
                deleteUser(uid);
            });
            if (listUsersResult.pageToken) {
                getAllUsers(listUsersResult.pageToken);
            }
        })
        .catch(function(error) {
            console.log('Error listing users:', error);
        });
}

getAllUsers();


问:
Calendar - Apply search filter on appointments (Subject)
I am using the EWS Java api 2.0 to read appointments on a Calendar mailbox.
It works fine but my problem is to filter the appointments by its subject description, which I am not succeeding.
At the moment I am using CalendarView to retrieve the appointments,
something like this:

```<code>CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
CalendarView view = new CalendarView(startDate, endDate);
FindItemsResults<Appointment> findResults3 = cf.findAppointments(view);
</code>```

I know that the Item class provides a method which I can apply a search filter, but it does return occurrences of a recurring series.

Something like that:

```<code>ItemView itemView = new ItemView(50);
SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "OK");
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, searchFilter, itemView);
</code>```

Does anyone have an idea how to fix that?

Thanks and regards

答:
After using FindItems you will get all the recurring masters, which represents the whole series. From masters you can get occurrences and exceptions:

```<code>Appointment occurrenceOrException = Appointment.BindToOccurrence(service, new ItemId(recurringMasterId), index);
</code>```

with the above you can get occurrence/exception by index.
Note that index starts from 1 and when index is out of range it will throw an exception.

This might help: https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633700%28v%3dexchg.80%29

Body:
I am using the EWS Java api 2.0 to read appointments on a Calendar mailbox.
It works fine but my problem is to filter the appointments by its subject description, which I am not succeeding.
At the moment I am using CalendarView to retrieve the appointments,
something like this:

CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
CalendarView view = new CalendarView(startDate, endDate);
FindItemsResults<Appointment> findResults3 = cf.findAppointments(view);

I know that the Item class provides a method which I can apply a search filter, but it does return occurrences of a recurring series.

Something like that:

ItemView itemView = new ItemView(50);
SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "OK");
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, searchFilter, itemView);

Does anyone have an idea how to fix that?

Thanks and regards

Body:
After using FindItems you will get all the recurring masters, which represents the whole series. From masters you can get occurrences and exceptions:

Appointment occurrenceOrException = Appointment.BindToOccurrence(service, new ItemId(recurringMasterId), index);

with the above you can get occurrence/exception by index.
Note that index starts from 1 and when index is out of range it will throw an exception.

This might help: https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633700%28v%3dexchg.80%29


问:
Modal component renders Twice on open
I'm using react-spring to animate a Modal based on @reach/dialog. The Modal can have any children. In the children I'm fetching some data based on some prop.

The problem is that the fetch call is made two times on opening the modal. I think it has probably to do with how I'm managing the state and that is causing re-renders.

I'v tried memoizing the children inside the modal and it didn't work, so I think that the problem is outside of the Modal component.

Here is something close to my code and how it is working  https://codesandbox.io/s/loving-liskov-1xouh

EDIT: I already know that if I remove the react-spring animation the double rendering doesn't happen, but I want to try keeping the animation intact.

Do you think you can help me to identify where is the bug? (Also some tips on good practice with hooks are highly appreciated).

答:
I checked and it is rendered twice because of animation in a Modal component when an animation is finished, modal is rendered second time when I commented out fragment responsible for animation, Modal renders only once.</p>

```<code> const Modal = ({ children, toggle, isOpen }) => {
  // const transitions = useTransition(isOpen, null, {
  //   from: { opacity: 0 },
  //   enter: { opacity: 1 },
  //   leave: { opacity: 0 }
  // });
  console.log("render");
  const AnimatedDialogOverlay = animated(DialogOverlay);
  // return transitions.map(
  //   ({ item, key, props }) =>
  //     item && (
    return (
        <AnimatedDialogOverlay isOpen={isOpen}>
          <DialogContent>
            <div
              style={{
                display: `flex`,
                width: `100%`,
                alignItems: `center`,
                justifyContent: `space-between`
              }}
            >
              <h2 style={{ margin: `4px 0` }}>Modal Title</h2>
              <button onClick={toggle}>Close</button>
            </div>
            {children}
          </DialogContent>
        </AnimatedDialogOverlay>
    );
  //     )
  // );
};
</code>```

Title: Modal component renders Twice on open

Body:
I checked and it is rendered twice because of animation in a Modal component when an animation is finished, modal is rendered second time when I commented out fragment responsible for animation, Modal renders only once.

 const Modal = ({ children, toggle, isOpen }) => {
  // const transitions = useTransition(isOpen, null, {
  //   from: { opacity: 0 },
  //   enter: { opacity: 1 },
  //   leave: { opacity: 0 }
  // });
  console.log("render");
  const AnimatedDialogOverlay = animated(DialogOverlay);
  // return transitions.map(
  //   ({ item, key, props }) =>
  //     item && (
    return (
        <AnimatedDialogOverlay isOpen={isOpen}>
          <DialogContent>
            <div
              style={{
                display: `flex`,
                width: `100%`,
                alignItems: `center`,
                justifyContent: `space-between`
              }}
            >
              <h2 style={{ margin: `4px 0` }}>Modal Title</h2>
              <button onClick={toggle}>Close</button>
            </div>
            {children}
          </DialogContent>
        </AnimatedDialogOverlay>
    );
  //     )
  // );
};


问:
How to add jars inside another war file for Maven dependencies?
I have a legacy ant project that takes a third party war, unjars it and then uses the resources and libraries (100+ jars) inside it for the Build.

In Maven, I am able to get this war file from the repository and unpack it. But how do I include the jars in the unpacked directory for compilation?

Also, how do I make sure that the compile happens after the unpack?

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="\[http://maven.apache.org/POM/4.0.0\](http://maven.apache.org/POM/4.0.0)" xmlns:xsi="\[http://www.w3.org/2001/XMLSchema-instance\](http://www.w3.org/2001/XMLSchema-instance)" xsi:schemaLocation="\[http://maven.apache.org/POM/4.0.0\](http://maven.apache.org/POM/4.0.0) \[http://maven.apache.org/xsd/maven-4.0.0.xsd\](http://maven.apache.org/xsd/maven-4.0.0.xsd)">
<modelVersion>4.0.0</modelVersion>
<groupId>project1</groupId>
<artifactId>project1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project1 Maven Webapp</name>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.abc.third-party</groupId>
                                <artifactId>externalWar</artifactId>
                                <version>1.0.0</version>
                                <type>war</type>
                                <overWrite>false</overWrite>
                                <outputDirectory>target</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</project>
</code>```

答: As a first step, try to bind the dependency plugin to a lifecycle phase running before the compile, e.g.: generate-sources. So you ensure the unpacked sources to exist while the compile phase runs.

Body:
I have a legacy ant project that takes a third party war, unjars it and then uses the resources and libraries (100+ jars) inside it for the Build.

In Maven, I am able to get this war file from the repository and unpack it. But how do I include the jars in the unpacked directory for compilation?

Also, how do I make sure that the compile happens after the unpack?

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="\[http://maven.apache.org/POM/4.0.0\](http://maven.apache.org/POM/4.0.0)" xmlns:xsi="\[http://www.w3.org/2001/XMLSchema-instance\](http://www.w3.org/2001/XMLSchema-instance)" xsi:schemaLocation="\[http://maven.apache.org/POM/4.0.0\](http://maven.apache.org/POM/4.0.0) \[http://maven.apache.org/xsd/maven-4.0.0.xsd\](http://maven.apache.org/xsd/maven-4.0.0.xsd)">
<modelVersion>4.0.0</modelVersion>
<groupId>project1</groupId>
<artifactId>project1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project1 Maven Webapp</name>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.abc.third-party</groupId>
                                <artifactId>externalWar</artifactId>
                                <version>1.0.0</version>
                                <type>war</type>
                                <overWrite>false</overWrite>
                                <outputDirectory>target</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</project>


问:
Combining Radio button values into a hidden form element using jquery or javascript
I have form where people search for a profile match on two values. In this case their role Specialist, Doctor or Nurse and their ranking - Gold, Silver or Bronze.

I need to be able to join these values and send to a hidden input which is submitted with the form. For example <input name="Icon" type="hidden" value="NurseSilver" />  is then used to determine which icon can be represented on a map that's returned. My code is looking something like this...

```<code><input type="radio" name="role" value="Specialist" id="role1" />
<input type="radio" name="role" value="Doctor" id="role2" />
<input type="radio" name="role" value="Nurse" id="role3" />

<input type="radio" name="rank" value="Gold" id="rank1" />
<input type="radio" name="rank" value="Silver" id="rank2" />
<input type="radio" name="rank" value="Bronze" id="rank3" />

<input name="Icon" type="hidden" value="" />
</code>```

Thanks for looking...

答:
```<code>$('input[type=radio]').change(function(){
   $('input[name=Icon]').val(
      $('input[name=role]:checked').val()+
      $('input[name=rank]:checked').val()
   );
});
</code>```

Body:
I have form where people search for a profile match on two values. In this case their role Specialist, Doctor or Nurse and their ranking - Gold, Silver or Bronze.

I need to be able to join these values and send to a hidden input which is submitted with the form. For example <input name="Icon" type="hidden" value="NurseSilver" />  is then used to determine which icon can be represented on a map that's returned. My code is looking something like this...

<input type="radio" name="role" value="Specialist" id="role1" />
<input type="radio" name="role" value="Doctor" id="role2" />
<input type="radio" name="role" value="Nurse" id="role3" />

<input type="radio" name="rank" value="Gold" id="rank1" />
<input type="radio" name="rank" value="Silver" id="rank2" />
<input type="radio" name="rank" value="Bronze" id="rank3" />

<input name="Icon" type="hidden" value="" />

Thanks for looking...


问:
Clojure returning simple true or false from a function
I am new to Clojure and i am having trouble with the basics of it. I am trying to write a simple if else program and use it in recursion but i am having trouble with the syntax. The code in Java is :

```<code>if(a > 0 && b >0){
   return true;
}else{
  return false;
}
</code>```

The code in clojure should be :

```<code>(defn checkPositiveNumber
    [x y]
    (if (and (> x 0) (> y 0))
            (do
                (def val true)
            )
            (do
                (def val false)
    )
)

(println (checkPositiveNumber 2 3))
</code>```

returns #'user/val instead of false.
What am i doing wrong ? This function should return true or false as i will be using it to either terminate my recursion or to check further.

Edit:
Thanks to Lee i was able to achieve the thing i asked... But my real purpose is :

```<code>if(a > 0 && b >0){
       System.out.println("Values are Positive");
       return true;
    }else{
      System.out.println("Some Values are Negative");
      return false;
    }
</code>```

答:
There is no analogue of return in clojure. Clojure function bodies are expressions so you need to organise your function to evaluate to true or false for each case.

In this case you don't need to use if at all:

```<code>(defn checkPositiveNumber [x y]
  (and (> x 0) (> y 0)))
</code>```

if you want to execute some side-effect in each branch you can use do:

```<code>(defn checkPositiveNumber [x y]
   (if (and (> x 0) (> y 0)))
     (do
       (println "x and y both positive")
       true)
     (do
       (println "One of x or y non-positive")
       false)))
</code>```

Body:
I am new to Clojure and i am having trouble with the basics of it. I am trying to write a simple if else program and use it in recursion but i am having trouble with the syntax. The code in Java is :

if(a > 0 && b >0){
   return true;
}else{
  return false;
}

The code in clojure should be :

(defn checkPositiveNumber
    [x y]
    (if (and (> x 0) (> y 0))
            (do
                (def val true)
            )
            (do
                (def val false)
    )
)

(println (checkPositiveNumber 2 3))

returns #'user/val instead of false.
What am i doing wrong ? This function should return true or false as i will be using it to either terminate my recursion or to check further.

Edit:
Thanks to Lee i was able to achieve the thing i asked... But my real purpose is :

if(a > 0 && b >0){
       System.out.println("Values are Positive");
       return true;
    }else{
      System.out.println("Some Values are Negative");
      return false;
    }

Body:
There is no analogue of return in clojure. Clojure function bodies are expressions so you need to organise your function to evaluate to true or false for each case.

In this case you don't need to use if at all:

(defn checkPositiveNumber [x y]
  (and (> x 0) (> y 0)))

if you want to execute some side-effect in each branch you can use do:

(defn checkPositiveNumber [x y]
   (if (and (> x 0) (> y 0)))
     (do
       (println "x and y both positive")
       true)
     (do
       (println "One of x or y non-positive")
       false)))


问:
Java script key value pair to object
I  am new to javascript. I have an array of data in the format:

```<code>Toronto, Ontario: 95
Markham, Ontario: 71
</code>```

I want to convert it to an array of object:

 Like this, to be consistent with other functions.

I tried:

```<code>reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        city: city,
        value: reportData.city[city]
    };
});
</code>```

What I get is:
{city: "Markham, Ontario": "value": 71}

答:
```<code>reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        [city]: reportData.city[city]
    };
})
</code>```

Title: Java script key value pair to object

Body:
I  am new to javascript. I have an array of data in the format:

Toronto, Ontario: 95
Markham, Ontario: 71

I want to convert it to an array of object:

 Like this, to be consistent with other functions.

I tried:

reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        city: city,
        value: reportData.city[city]
    };
});

What I get is:
{city: "Markham, Ontario": "value": 71}


问:
What is the correct approach to check if array exists in JS?
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

```<code>if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}
</code>```

Error

```<code>TypeError: Cannot read property 'length' of undefined
</code>```

答:
You do not really need to actually do the .length !== 0. You can simply do:

```<code>if (Array.isArray(A.B.C) && A.B.C.length) {  // <-- order is important here
    //...
}
</code>```

.length would be evaluated as a boolean and it will give you the same result as checking with !==0

That being said however your paths are quite long so you probably would want to make sure they are valid. Meaning if drugPrice or mailPrice are falsey you would have an issue. So usually you would want to check on them as well. Since your question was about the array part I will skip those but just as FYI.

You can build your own path checker or if you use libraries like lodash/underscore etc they always have a handy get/has functions to check like this (with lodash):

```<code>if (_.has(drugPrice, 'mailPrice.rejectMessage.length'))
    //...
}
</code>```

Obviously do not use those libraries just for that but if you already have them those methods are quite handy. You can simply check each of the paths as well via:

```<code>if (A && A.B && Array.isArray(A.B.C) && A.B.C.length) {
    //...
}
</code>```

It just gets tedious if you have long object paths etc.

Body:
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}

Error

TypeError: Cannot read property 'length' of undefined

Body:
You do not really need to actually do the .length !== 0. You can simply do:

if (Array.isArray(A.B.C) && A.B.C.length) {  // <-- order is important here
    //...
}

.length would be evaluated as a boolean and it will give you the same result as checking with !==0

That being said however your paths are quite long so you probably would want to make sure they are valid. Meaning if drugPrice or mailPrice are falsey you would have an issue. So usually you would want to check on them as well. Since your question was about the array part I will skip those but just as FYI.

You can build your own path checker or if you use libraries like lodash/underscore etc they always have a handy get/has functions to check like this (with lodash):

if (_.has(drugPrice, 'mailPrice.rejectMessage.length'))
    //...
}

Obviously do not use those libraries just for that but if you already have them those methods are quite handy. You can simply check each of the paths as well via:

if (A && A.B && Array.isArray(A.B.C) && A.B.C.length) {
    //...
}

It just gets tedious if you have long object paths etc.


问:
How to edit the nodes of the built-in robot
I found that in the latest version of webots (2019a), it is not possible to edit the model tree nodes of the built-in robots. They seem to be encapsulated and there are no Children nodes. I hope to learn modeling with examples of built-in robots, but in previous versions (version 7.0.3) it was editable.</p>

答:
Robot definitions are indeed most of the time encapsulated in what we call a PROTO nodes.

PROTO description: https://www.cyberbotics.com/doc/reference/proto

Tutorial on how to create your own PROTO node: https://www.cyberbotics.com/doc/guide/tutorial-7-your-first-proto

But you can remove this 'encapsulation' simply by right-clicking in the scene tree on the node and selecting 'Convert to Base Node(s)'. This will completely 'unprototize' the node and you will be able to see the complete hierarchy (including the 'children' nodes)


问:
Text input to have whatever left as width
I want to have a Tags input (just like the stackoverflow's one) where users can type their chosen tags and it shows inside the input.
I decided to do it inside of a ul where the input is the last li:

```<code>  <ul class="tag-box">
    <li class="tags" *ngFor="let tag of tags">{{tag.name}}<a class="close"></a></li>
    <li class="new-tag"><input class="input-tag" type="text"></li>
  </ul>
</code>```

But the problem is the width of the input is always small by default while I want it to take all the remaining width:

my css:

```<code>.tag-box {
  list-style: none;
  padding: 3px;
  margin: 0;
  display: inline-block;
  font-family: arial;
  width: 100%;
  border: 1px solid #F39F19;
  border-radius: 4px;
}
.tag-box li {
  padding: 4px 6px;
  float: left;
  display: inline-block;
}
.tag-box li.tags {
  background: #F1C617;
  color: #fff;
  border-radius: 4px;
  margin: 4px 3px;
  position: relative;
}
.tag-box li .input-tag {
  color: #000;
  height: 24px;
  vertical-align: middle;
  border: none;
  outline: none;
  background: none;
}
</code>```

Is there a way where my input my input can take whatever left of space as width according to the loop?

答:
Here's one way you could do it, I'm adding 3 things. You'll eventually want to give it a min-width and make it wrap though.

.tag-box {
  display: flex;
}
.tag-box .new-tag {
  flex: 1
}
.tag-box li .input-tag {
  width: 100%;
}```

Body:
I want to have a Tags input (just like the stackoverflow's one) where users can type their chosen tags and it shows inside the input.
I decided to do it inside of a ul where the input is the last li:

{{tag.name}}

<input class="input-tag" type="text">

But the problem is the width of the input is always small by default while I want it to take all the remaining width:

my css:

.tag-box {
  list-style: none;
  padding: 3px;
  margin: 0;
  display: inline-block;
  font-family: arial;
  width: 100%;
  border: 1px solid #F39F19;
  border-radius: 4px;
}
.tag-box li {
  padding: 4px 6px;
  float: left;
  display: inline-block;
}
.tag-box li.tags {
  background: #F1C617;
  color: #fff;
  border-radius: 4px;
  margin: 4px 3px;
  position: relative;
}
.tag-box li .input-tag {
  color: #000;
  height: 24px;
  vertical-align: middle;
  border: none;
  outline: none;
  background: none;
}

Is there a way where my input my input can take whatever left of space as width according to the loop?


问:
Create AWS Athena view programmatically
Can you create views in Amazon Athena? outlines how to create a view using the User Interface.

I'd like to create an AWS Athena View programatically, ideally using Terraform (which calls CloudFormation).

I followed the steps outlined here: https://ujjwalbhardwaj.me/post/create-virtual-views-with-aws-glue-and-query-them-using-athena, however I run into an issue with this in that the view goes stale quickly.

...._view' is stale; it must be re-created.

The terraform code looks like this:

```<code>resource "aws_glue_catalog_table" "adobe_session_view" {

  database_name = "${var.database_name}"
  name = "session_view"

  table_type = "VIRTUAL_VIEW"
  view_original_text = "/* Presto View: ${base64encode(data.template_file.query_file.rendered)} */"
  view_expanded_text = "/* Presto View */"

  parameters = {
    presto_view = "true"
    comment = "Presto View"
  }

  storage_descriptor {
    ser_de_info {
      name = "ParquetHiveSerDe"
      serialization_library = "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"
    }

    columns { name = "first_column" type = "string" }
    columns { name = "second_column" type = "int" }
    ...
    columns { name = "nth_column" type = "string" }
}
</code>```

An alternative I'd be happy to use is the AWS CLI, however aws athena [option] provides no option for this.

I've tried:

create-named-query which I have not been able to get working for a statement such as CREATE OR REPLACE VIEW as this doesn't seem to be the intended use case for this command.

start-query-execution which asks for an output location, which suggests that this is meant for querying the data and outputting the results, as opposed to making stateful changes/creations. It also seems to be paired with stop-query-execution.

答:
To add to the answers by JD D and Theo, working with their solutions, we have figured out how to invoke the AWS Cli via terraform in the following:

```<code>resource "null_resource" "athena_view" {

  provisioner "local-exec" {
    command = <<EOF
aws sts assume-role \
  --output json \
  --region my_region \
  --role-arn arn:aws:iam::${var.account_number}:role/my_role \
  --role-session-name create_my_view > /tmp/credentials.json

export AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' /tmp/credentials.json)
export AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' /tmp/credentials.json)
export AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' /tmp/credentials.json)

aws athena start-query-execution \
  --output json \
  --region my_region \
  --query-string "CREATE OR REPLACE VIEW my_view AS SELECT * FROM my_table \
  --query-execution-context "Database=${var.database_name}" \
  --result-configuration "OutputLocation=s3://${aws_s3_bucket.my-bucket.bucket}"
EOF
  }
}
</code>```

We use null_resource ... to run provisioners that aren't directly associated with a specific resource.

The result of aws sts assume-role is outputted as JSON into /tmp/credentials.json.

jq is used to parse the necessary fields out of the output of aws sts assume-role .

aws athena start-query-execution is then able to execute under the role specified by the environment variables defined.

Instead of --result-configuration "OutputLocation=s3://...., --work-group can be specified, NOTE that this is a separate flag on start-query-execution, not part of the --result-configuration string.

Title: Create AWS Athena view programmatically

Body:
Can you create views in Amazon Athena? outlines how to create a view using the User Interface.

I'd like to create an AWS Athena View programatically, ideally using Terraform (which calls CloudFormation).

I followed the steps outlined here: https://ujjwalbhardwaj.me/post/create-virtual-views-with-aws-glue-and-query-them-using-athena, however I run into an issue with this in that the view goes stale quickly.

...._view' is stale; it must be re-created.

The terraform code looks like this:

resource "aws_glue_catalog_table" "adobe_session_view" {

  database_name = "${var.database_name}"
  name = "session_view"

  table_type = "VIRTUAL_VIEW"
  view_original_text = "/* Presto View: ${base64encode(data.template_file.query_file.rendered)} */"
  view_expanded_text = "/* Presto View */"

  parameters = {
    presto_view = "true"
    comment = "Presto View"
  }

  storage_descriptor {
    ser_de_info {
      name = "ParquetHiveSerDe"
      serialization_library = "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"
    }

    columns { name = "first_column" type = "string" }
    columns { name = "second_column" type = "int" }
    ...
    columns { name = "nth_column" type = "string" }
}

An alternative I'd be happy to use is the AWS CLI, however aws athena [option] provides no option for this.

I've tried:

create-named-query which I have not been able to get working for a statement such as CREATE OR REPLACE VIEW as this doesn't seem to be the intended use case for this command.

start-query-execution which asks for an output location, which suggests that this is meant for querying the data and outputting the results, as opposed to making stateful changes/creations. It also seems to be paired with stop-query-execution.

Body:
To add to the answers by JD D and Theo, working with their solutions, we have figured out how to invoke the AWS Cli via terraform in the following:

resource "null_resource" "athena_view" {

  provisioner "local-exec" {
    command = <<EOF
aws sts assume-role \
  --output json \
  --region my_region \
  --role-arn arn:aws:iam::${var.account_number}:role/my_role \
  --role-session-name create_my_view > /tmp/credentials.json

export AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' /tmp/credentials.json)
export AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' /tmp/credentials.json)
export AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' /tmp/credentials.json)

aws athena start-query-execution \
  --output json \
  --region my_region \
  --query-string "CREATE OR REPLACE VIEW my_view AS SELECT * FROM my_table \
  --query-execution-context "Database=${var.database_name}" \
  --result-configuration "OutputLocation=s3://${aws_s3_bucket.my-bucket.bucket}"
EOF
  }
}

We use null_resource ... to run provisioners that aren't directly associated with a specific resource.

The result of aws sts assume-role is outputted as JSON into /tmp/credentials.json.

jq is used to parse the necessary fields out of the output of aws sts assume-role .

aws athena start-query-execution is then able to execute under the role specified by the environment variables defined.

Instead of --result-configuration "OutputLocation=s3://...., --work-group can be specified, NOTE that this is a separate flag on start-query-execution, not part of the --result-configuration string.


问:
Query to get data for past X months in JPQL
I have constructed following JPQL query where result is being sent based on the timestamp being passed in.
I am looking to modify this and pass in a number instead which is the month value and get all results from past 6 months for example.

I am using Oracle DB if that is relevant. I tried passing in datediff method in this query but it is throwing compilation errors.
Is there a way to do this?

My current query.

```<code>@Query("SELECT SUM(urlCount.referEventTotalCount) " +
            "FROM UrlCountEntity urlCount " +
            "JOIN urlCount.eventTypes et " +
            "WHERE urlCount.url.urlTx IN :urls " +
            "AND et.referEventTypeDs =:eventType " +
            "AND urlCount.updateTimeStamp <=:timeStamp")
    Integer getTotalCount(@Param("urls") List<String> urls, @Param("eventType")String eventType, @Param("timeStamp")Timestamp timeStamp);
</code>```

Looking to modify the line -> "AND urlCount.updateTimeStamp <=:timeStamp")

```<code>  @Query("SELECT SUM(urlCount.referEventTotalCount) " +
            "FROM UrlCountEntity urlCount " +
            "JOIN urlCount.eventTypes et " +
            "WHERE urlCount.url.urlTx IN :urls " +
            "AND et.referEventTypeDs =:eventType ")
            // "AND urlCount.updateTimeStamp <=:timeStamp") // instead of this, pass in the numOfMths value to calculate how much data to show (example past 3 mths)
  Integer getTotalCount(@Param("urls") List<String> urls, @Param("eventType")String eventType, @Param("numOfMths")int numOfMths);
</code>```

答:
With Oracle you can use ADD_MONTH with a negativ value to subtract.

```<code>ADD_MONTHS(SYSDATE, -6)
</code>```

You can call this functions like this:

```<code>function('ADD_MONTH', CURRENT_DATE, -6)
</code>```

So your query could look like this:

```<code> @Query("SELECT SUM(urlCount.referEventTotalCount) " +
        "FROM UrlCountEntity urlCount " +
        "JOIN urlCount.eventTypes et " +
        "WHERE urlCount.url.urlTx IN :urls " +
        "AND et.referEventTypeDs =:eventType " +
        "AND urlCount.updateTimeStamp >= function('ADD_MONTH', CURRENT_DATE, :month)")
</code>```

Body:
I have constructed following JPQL query where result is being sent based on the timestamp being passed in.
I am looking to modify this and pass in a number instead which is the month value and get all results from past 6 months for example.

I am using Oracle DB if that is relevant. I tried passing in datediff method in this query but it is throwing compilation errors.
Is there a way to do this?

My current query.

@Query("SELECT SUM(urlCount.referEventTotalCount) " +
            "FROM UrlCountEntity urlCount " +
            "JOIN urlCount.eventTypes et " +
            "WHERE urlCount.url.urlTx IN :urls " +
            "AND et.referEventTypeDs =:eventType " +
            "AND urlCount.updateTimeStamp <=:timeStamp")
    Integer getTotalCount(@Param("urls") List<String> urls, @Param("eventType")String eventType, @Param("timeStamp")Timestamp timeStamp);

Looking to modify the line -> "AND urlCount.updateTimeStamp <=:timeStamp")

  @Query("SELECT SUM(urlCount.referEventTotalCount) " +
            "FROM UrlCountEntity urlCount " +
            "JOIN urlCount.eventTypes et " +
            "WHERE urlCount.url.urlTx IN :urls " +
            "AND et.referEventTypeDs =:eventType ")
            // "AND urlCount.updateTimeStamp <=:timeStamp") // instead of this, pass in the numOfMths value to calculate how much data to show (example past 3 mths)
  Integer getTotalCount(@Param("urls") List<String> urls, @Param("eventType")String eventType, @Param("numOfMths")int numOfMths);

Body:
With Oracle you can use ADD_MONTH with a negativ value to subtract.

ADD_MONTHS(SYSDATE, -6)

You can call this functions like this:

function('ADD_MONTH', CURRENT_DATE, -6)

So your query could look like this:

 @Query("SELECT SUM(urlCount.referEventTotalCount) " +
        "FROM UrlCountEntity urlCount " +
        "JOIN urlCount.eventTypes et " +
        "WHERE urlCount.url.urlTx IN :urls " +
        "AND et.referEventTypeDs =:eventType " +
        "AND urlCount.updateTimeStamp >= function('ADD_MONTH', CURRENT_DATE, :month)")


问:
How to push an array to state in React? Getting "Invalid attempt to spread non-iterable instance"
I'm trying to push a movie object into a favorites array in state when something is clicked.

Setting the favoritesArray into state works:

```<code>addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState({favorites: favoritesArray});
}
</code>```

But when I try to use an updater function as recommended by React I get errors:

```<code>this.state = {
  favorites: []
};

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState(prevState => ({
    favorites: [...prevState.favorites, favoritesArray]
  }))
}
</code>```

Uncaught TypeError: Invalid attempt to spread non-iterable instance

It does seem to work if there's already something in state (not an empty array).

答:
You have a missmatch in your types, you are adding an array as an element of another array (which I believe is not what you wanted). Also, you can prevent spreading an empty state.favorites in the updater function. The following code should work:

```<code>addToFavorites = (movie) => {
    this.setState(prevState => ({
        favorites: [...(prevState.favorites || []), movie]
    }));
}
</code>```

The ...(prevState.favorites || []) makes sure that the spread does not fail in case prevState.favorites is null or undefined.

Body:
I'm trying to push a movie object into a favorites array in state when something is clicked.

Setting the favoritesArray into state works:

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState({favorites: favoritesArray});
}

But when I try to use an updater function as recommended by React I get errors:

this.state = {
  favorites: []
};

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState(prevState => ({
    favorites: [...prevState.favorites, favoritesArray]
  }))
}

Uncaught TypeError: Invalid attempt to spread non-iterable instance

It does seem to work if there's already something in state (not an empty array).

Body:
You have a missmatch in your types, you are adding an array as an element of another array (which I believe is not what you wanted). Also, you can prevent spreading an empty state.favorites in the updater function. The following code should work:

addToFavorites = (movie) => {
    this.setState(prevState => ({
        favorites: [...(prevState.favorites || []), movie]
    }));
}

The ...(prevState.favorites || []) makes sure that the spread does not fail in case prevState.favorites is null or undefined.


问:
swf file size issue in internet explorer
I have swf file, the firefox and chrome displays the swf files as per the mentioned width and height. But in Internet explorer, the swf file is too small than the other browsers.

Any idea to fix?

Thanks in advance.

答: In "object" if you delete attribute "class" then you'll have normal size in IE,opera,ff. In Chrome will be smaller.</p>

ContentLicense: CC BY-SA 2.5


问:
Javascript SyntaxError redeclaration of class
i'm starting using Javascript OOP, i writed my first class but i get an message error in the console

this is Class :

```<code>class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var Quote = new Quote();
</code>```

this is the error :

```<code>SyntaxError: redeclaration of class Quote quote.js:9:4note: Previously declared at line 1, column 6
</code>```

答:
Just change the variable name, because classes are also variables in javascript

var Quote = new Quote();

to any other name like

var quote = new Quote();

Body:
i'm starting using Javascript OOP, i writed my first class but i get an message error in the console

this is Class :

class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var Quote = new Quote();

this is the error :

SyntaxError: redeclaration of class Quote quote.js:9:4note: Previously declared at line 1, column 6


问:
Linear gradient is showing two colors despite only one being specified
I'm trying to understand how a linear gradient with only one color specified is producing a background with two different colors.

.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
  linear-gradient(
      to bottom,
      #238d82 16px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    )
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book-bg"></div></code>```

I would expect this linear gradient to produce a background with only #238d82. The rgba value (rgba(35, 141, 130, 0)) converts to the same hex code so shouldn't this div just be one color? What is causing the dark strip at the top?

答:
```<code>.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
    linear-gradient(
      to bottom,
      #238d82 0px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    );
}
</code>```

Start colour of a linear gradient function is starting from 16px because of which you are seeing a dark strip at the top.

Body:
I'm trying to understand how a linear gradient with only one color specified is producing a background with two different colors.

.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
  linear-gradient(
      to bottom,
      #238d82 16px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    )
}

I would expect this linear gradient to produce a background with only #238d82. The rgba value (rgba(35, 141, 130, 0)) converts to the same hex code so shouldn't this div just be one color? What is causing the dark strip at the top?

Body:
.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
    linear-gradient(
      to bottom,
      #238d82 0px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    );
}

Start colour of a linear gradient function is starting from 16px because of which you are seeing a dark strip at the top.


答:
Based on your updated question, I take it that you have this:

```<code>const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
</code>```

and you want this:

```<code>result = [
    {"Toronto, Ontario": 95},
    {"Markham, Ontario": 71}
];
</code>```

To do that, you need to split the number at the end of the string off, and then build objects with the two parts of the string. If you know there's only ever one :, then:

```<code>const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});
</code>```

Live Example:

const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});
console.log(result);```

That uses destructuring to capture the two parts from split, then a computed property name to create a property with the city name, and + to coerce the number to number from string. (That's just one of your number-to-string options, see this answer for more options.)

Title: Java script key value pair to object

Body:
Based on your updated question, I take it that you have this:

const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];

and you want this:

result = [
    {"Toronto, Ontario": 95},
    {"Markham, Ontario": 71}
];

To do that, you need to split the number at the end of the string off, and then build objects with the two parts of the string. If you know there's only ever one :, then:

const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});

Live Example:

const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
const result = start.map(str => {
    const [city, number] = str.split(":");
    return {
        [city]: +number
    };
});
console.log(result);

That uses destructuring to capture the two parts from split, then a computed property name to create a property with the city name, and + to coerce the number to number from string. (That's just one of your number-to-string options, see this answer for more options.)


问:
EU Consent Form Loads Without Internet Connection
I am implementing EU Consent in two iOS apps.
As required I am putting an update consent button in the settings of my app in case the user wants to change their consent.
The consent form loads if there is no internet connection and the dialog box responds to clicking the buttons with no errors.
If the Internet connection has dropped out the user will believe that consent has been updated when it hasn't.

Am I missing something.  There doesn't seem to be a callback from AdMob to confirm change of status.

答: I had similar issue. I solved it by disabling button when there is no internet connection and displaying alert that says consent status cannot be updated without internet connection.</p>


问:
Android: Gapless playback of a looped audio file in MediaPlayer
I am playing a setLooped enabled audio file in my app, but every time the audio file loops, there is a noticeable, though very brief, gap in the audio playback... is there any way to get around this?</p>

答: I was just facing the same problem and I guess you have been using MP3 or OGG files or some other compressed format. The solution is to use WAV files instead. This may increase your apk size but lets you loop gapless.</p>


问:
Multiple IF statements between number ranges
I'm trying to set up a formula with multiple IF statements between number ranges but I'm seeing the error:

Formula parse error

Here is the forumula:

```<code>=IF((AND(A2>0,A2<500),"Less than 500",
 If(AND(A2>=500,A2<1000),"Between 500 and 1000"),
 If(AND(A2>=1000,A2<1500),"Between 1000 and 1500"),
 If(AND(A2>=1500,A2<2000),"Between 1500 and 2000")))
</code>```

答:
Shorter than accepted A, easily extensible and addresses 0 and below:

```<code>=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1)))
</code>```

Body:
I'm trying to set up a formula with multiple IF statements between number ranges but I'm seeing the error:

Formula parse error

Here is the forumula:

=IF((AND(A2>0,A2<500),"Less than 500",
 If(AND(A2>=500,A2<1000),"Between 500 and 1000"),
 If(AND(A2>=1000,A2<1500),"Between 1000 and 1500"),
 If(AND(A2>=1500,A2<2000),"Between 1500 and 2000")))

Body:
Shorter than accepted A, easily extensible and addresses 0 and below:

=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1)))


问:
Recursion to print number by using return statement
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}
</code>```

but I want to do this with the following way.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}
</code>```

Expected output:

```<code>2,1,0
</code>```

but it shows:

```<code>2,1
</code>```

Why does it happen?

答:
```<code>class Test {

    public static void main(String[] args) {
        rec(0);
    }

    private static void rec(int num){
        if(num <= 2){
            rec(num + 1);
        } else return;

        System.out.println(num);
    }

}
</code>```

++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.

When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.

Body:
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}

but I want to do this with the following way.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}

Expected output:

2,1,0

but it shows:

2,1

Why does it happen?

Body:
class Test {

    public static void main(String[] args) {
        rec(0);
    }

    private static void rec(int num){
        if(num <= 2){
            rec(num + 1);
        } else return;

        System.out.println(num);
    }

}

++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.

When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.


问:
In racket how do i combine strings in a list to create one sentence
Essentially I want to combine string values in a list.
For example I want
(Join(list "cat" "is" "hungry")) to execute ("cat is hungry")

(define(join l) )

答:
In Racket there's a procedure just for that, it's called string-join:

```<code>(string-join '("cat" "is" "hungry"))
=> "cat is hungry"
</code>```

Here's another alternative, using string-append. It's less efficient, but avoids having to code an explicit recursion:

```<code>(define (join lst)
  (foldl (lambda (s acc) (string-append acc " " s))
         (first lst)
         (rest  lst)))

(join '("cat" "is" "hungry"))
=> "cat is hungry"
</code>```

Body:
In Racket there's a procedure just for that, it's called string-join:

(string-join '("cat" "is" "hungry"))
=> "cat is hungry"

Here's another alternative, using string-append. It's less efficient, but avoids having to code an explicit recursion:

(define (join lst)
  (foldl (lambda (s acc) (string-append acc " " s))
         (first lst)
         (rest  lst)))

(join '("cat" "is" "hungry"))
=> "cat is hungry"


问:
Cleaning dupes and keeping max data
I have a table that contains duplicates and I need to keep the max data and blow away the rest. Due to requirements I cannot change the date field format and I am getting a conversion error. Any ideas?

```<code>DELETE from MAIN_TBL
WHERE ID NOT IN
(
select * from
(SELECT MAX(updated_on)
FROM MAIN_TBL
GROUP BY widget_tag, ID) as TEMP
)
</code>```

ERROR = Conversion failed when converting date and/or time from character string.

答:
You can use EXISTS:

```<code>DELETE t
from MAIN_TBL t
WHERE EXISTS (
  SELECT 1 FROM MAIN_TBL
  WHERE id = t.id and widget_tag = t.widget_tag and updated_on > t.updated_on
)
</code>```

See the demo.

Title: Cleaning dupes and keeping max data

Body:
I have a table that contains duplicates and I need to keep the max data and blow away the rest. Due to requirements I cannot change the date field format and I am getting a conversion error. Any ideas?

DELETE from MAIN_TBL
WHERE ID NOT IN
(
select * from
(SELECT MAX(updated_on)
FROM MAIN_TBL
GROUP BY widget_tag, ID) as TEMP
)

ERROR = Conversion failed when converting date and/or time from character string.

Body:
You can use EXISTS:

DELETE t
from MAIN_TBL t
WHERE EXISTS (
  SELECT 1 FROM MAIN_TBL
  WHERE id = t.id and widget_tag = t.widget_tag and updated_on > t.updated_on
)

See the demo.


问:
Does java support multiple inheritance?
Does java support multiple inheritance?
(https://i.stack.imgur.com/PkhMD.png)</p>

答:
If we are talking about classes and one class extend 2 other classes at the same time, the answer is no.

But, If you are using Java 8, you can achieve multiple inheritance with interfaces with default methods.

Check this here: https://www.geeksforgeeks.org/java-and-multiple-inheritance/

Title: Does java support multiple inheritance?


答:
The short answer is No.

But developers still wanted something similar so they created interfaces! A class can implement as many interfaces as you want!

A better explanation of what interfaces are, and how they can be used can be found at this link.

Title: Does java support multiple inheritance?

Body:
Does java support multiple inheritance?
(https://i.stack.imgur.com/PkhMD.png)


问:
Is there a way to produce animations beyond stacks of images in UIImage?
I'm fairly new to iOS development, and I was wondering: is there a way to produce animations on the iPhone besides creating a bunch of still images and animating them in a UIImageView?  What are the other methods for creating a moving animation on iOS?</p>

答:
Simple animations can be easily done by transforming views within the
[UIView beginAnimations: context:] and [UIView commitAnimations].

For example, to scale the current view, you would :

```<code>[UIView beginAnimations:@"auxviewclose" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
self.frame = CGRectMake(0, self.superview.frame.size.height-45, self.frame.size.width, 45);
[UIView commitAnimations];
</code>```

Body:
Simple animations can be easily done by transforming views within the
[UIView beginAnimations: context:] and [UIView commitAnimations].

For example, to scale the current view, you would :

[UIView beginAnimations:@"auxviewclose" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
self.frame = CGRectMake(0, self.superview.frame.size.height-45, self.frame.size.width, 45);
[UIView commitAnimations];


问:
create consumerGroup for iothub build-in endpoint via REST call from python with shared access policy
(how) is this possible?

two approaches:

1.

```<code>uri = 'https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s/consumergroups/%s?api-version=%s' % (subscriptionId,resourceGroupName,namespaceName,eventHubName,consumerGroupName,apiVersion)
</code>```

--> I am not able to create the header (authentication for the access)
with:

```<code>def get_auth_token(sb_name, eh_name, sas_name, sas_value): # Returns an authorization token dictionary for making calls to Event Hubs REST API.
    uri = quote_plus("https://{}.servicebus.windows.net/{}".format(sb_name, eh_name))
    sas = sas_value.encode('utf-8')
    expiry = str(int(time() + 10000))
    string_to_sign = (uri + '\n' + expiry).encode('utf-8')
    signed_hmac_sha256 = HMAC(sas, string_to_sign, sha256)
    signature = quote(b64encode(signed_hmac_sha256.digest()))
    return 'SharedAccessSignature sr={}&sig={}&se={}&skn={}'.format(uri, signature, expiry, sas_name)

header = { 'Authorization':get_auth_token(sb_name, eh_name, 'iothubowner', sas_value), 'Content-Type':'application/json' }
</code>```

2.

```<code>uri = '{sb_name}.servicebus.windows.net/{eh_name}/consumergroups'
header = { 'Authorization':get_auth_token(sb_name, eh_name, 'iothubowner', sas_value), 'Content-Type':'application/json' }
res = get(uri, headers=header) # this works (list of consumerGroups)
</code>```

but:

```<code>uri = '{sb_name}.servicebus.windows.net/{eh_name}/consumergroups/newConsumerGroup'
res = put(uri, headers=header)
</code>```

does not work:

```<code>401 40100: Unauthorized : Unauthorized access for 'CreateOrUpdateConsumerGroup' operation on endpoint 'sb://{sb_name}.servicebus.windows.net/{eh_name}/consumergroups/newConsumerGroup'.
</code>```

答:
Adding a consumer group to an Event Hub-compatible endpoint in the IoT Hub is described here.

That's your first option. Note, that this approach requires to use a Bearer Token for Authorization header.

Your second approach such as using a ServiceBus namespace and sas token for authorization is working well for any public Event Hub entity, but not for internal Event Hub of the IoT Hub. That's the reason why you can call only GET method. In other words, the Event Hub-compatible endpoint of the IoT Hub doesn't have a write permission.

Body:
(how) is this possible?

two approaches:

1.

uri = 'https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s/consumergroups/%s?api-version=%s' % (subscriptionId,resourceGroupName,namespaceName,eventHubName,consumerGroupName,apiVersion)

--> I am not able to create the header (authentication for the access)
with:

def get_auth_token(sb_name, eh_name, sas_name, sas_value): # Returns an authorization token dictionary for making calls to Event Hubs REST API.
    uri = quote_plus("https://{}.servicebus.windows.net/{}".format(sb_name, eh_name))
    sas = sas_value.encode('utf-8')
    expiry = str(int(time() + 10000))
    string_to_sign = (uri + '\n' + expiry).encode('utf-8')
    signed_hmac_sha256 = HMAC(sas, string_to_sign, sha256)
    signature = quote(b64encode(signed_hmac_sha256.digest()))
    return 'SharedAccessSignature sr={}&sig={}&se={}&skn={}'.format(uri, signature, expiry, sas_name)

header = { 'Authorization':get_auth_token(sb_name, eh_name, 'iothubowner', sas_value), 'Content-Type':'application/json' }

2.

uri = '{sb_name}.servicebus.windows.net/{eh_name}/consumergroups'
header = { 'Authorization':get_auth_token(sb_name, eh_name, 'iothubowner', sas_value), 'Content-Type':'application/json' }
res = get(uri, headers=header) # this works (list of consumerGroups)

but:

uri = '{sb_name}.servicebus.windows.net/{eh_name}/consumergroups/newConsumerGroup'
res = put(uri, headers=header)

does not work:

401 40100: Unauthorized : Unauthorized access for 'CreateOrUpdateConsumerGroup' operation on endpoint 'sb://{sb_name}.servicebus.windows.net/{eh_name}/consumergroups/newConsumerGroup'.


问:
JS / CSS issue with Div Slider and Display:Table-Cell
I have a Div slider that rotates a set of Divs in and out of focus. Everything was working fine until I tried switching everything to (table / table-cell) in order to keep them all the Divs the same height in CSS. Now they still rotate out but one div remains visible with a reduced width off to the side of the stage. I get a sense that its position related but just can't figure out what's causing the issue.

Affected Page - https://www.harpercollege.edu/dev/blog-slider-test.php

JS Code:

```<code>$('.blog-posts').wrapInner('<div class="blog-posts-stage" />');

// Calculate Conditions & Set Vars

// var playTimer = 9,
slideQty = $('.well').length,
  slideWidth = $('.well').width(),
  stageWidth = $('.blog-posts-stage').width(),
  contWidth = $('.blog-posts').width();

if ((slideQty * slideWidth) < contWidth) {
  $('.blog-posts-prev').addClass('blog-posts-prev-disabled').removeClass('blog-posts-prev');
  $('.blog-posts-next').addClass('blog-posts-next-disabled').removeClass('blog-posts-next');
} else {
  $('.blog-posts-prev-disabled').addClass('blog-posts-prev').removeClass('blog-posts-prev-disabled');
  $('.blog-posts-next-disabled').addClass('blog-posts-next').removeClass('blog-posts-next-disabled');
}

$(window).resize(function() {
  var slideQty = $('.well').length,
    slideWidth = $('.well').width(),
    stageWidth = $('.blog-posts-stage').width(),
    contWidth = $('.blog-posts').width();
  if ((slideQty * slideWidth) < contWidth) {
    $('.blog-posts-prev').addClass('blog-posts-prev-disabled').removeClass('blog-posts-prev');
    $('.blog-posts-next').addClass('blog-posts-next-disabled').removeClass('blog-posts-next');
  } else {
    $('.blog-posts-prev-disabled').addClass('blog-posts-prev').removeClass('blog-posts-prev-disabled');
    $('.blog-posts-next-disabled').addClass('blog-posts-next').removeClass('blog-posts-next-disabled');
  }
});

$('.blog-posts-next').on('click', function(event) {
  event.preventDefault();
  $('.blog-posts-stage').animate({
    left: -(slideWidth)
  }, 500, function() {
    $('.well:first').appendTo('.blog-posts-stage');
    $('.blog-posts-stage').css({
      left: '0px'
    });
  });
});

$('.blog-posts-prev').on('click', function(event) {
  event.preventDefault();
  $('.well:last').prependTo('.blog-posts-stage');
  $('.blog-posts-stage').css({
    left: -(slideWidth)
  });
  $('.blog-posts-stage').animate({
    left: '0px'
  }, 500, function() {});
});

function moveForward() {
  $('.blog-posts-stage').animate({
    left: -(slideWidth)
  }, 500, function() {
    $('.well:first').appendTo('.blog-posts-stage');
    $('.blog-posts-stage').css({
      left: '0px'
    });
  });
}
var timer = setInterval(moveForward, playTimer);

$('.blog-posts, .blog-posts-prev, .blog-posts-next').hover(function(ev) {
  // clearInterval(timer);
}, function(ev) {
  // timer = setInterval( moveForward, playTimer);
});
</code>```

CSS Code:

```<code><style>
    .blog-posts {
        width: 100%;
        background: #eee;
        font-size: 0;
        position: relative;
    }
    .blog-posts-prev,
    .blog-posts-next {
      display: inline-block;
      background: #eee;
      color: #000;
      text-decoration: none;
      padding: 10px;
      margin: 5px 0;
    }
    .blog-posts-prev:hover,
    .blog-posts-next:hover {
      background: #ccc;
    }
    .blog-posts-prev-disabled,
    .blog-posts-next-disabled {
      display: inline-block;
      background: #eee;
      color: #ccc;
      text-decoration: none;
      padding: 10px;
      margin: 5px 0;
    }
    .blog-posts-stage {
        position: relative;
        white-space: normal;
        width: 100%;
        height: 100%;
        float: none;
    }
    .well {
        background: #ccc;
        box-shadow: inset -1px 0px 0px 0px rgb(255, 255, 255);
        width: 100%;
        font-size: 12px;
        text-align: left;
        display: table-cell;
        height: 100%;
        width: 100%;
    }
    .well .row .col-sm-12.col-md-12 h2 {
        float: left;
        margin-top: 0px;
    }
</style>
</code>```

答:
You could just use a lightbox library and save yourself the effort, but if you really want to do this why not try flex?</p>

```<code>.blog-posts-stage {
  display: flex;
  flex-direction: row;
  overflow: hidden;
}

.well-large {
  flex-shrink: 0;
}
</code>```

Body:
I have a Div slider that rotates a set of Divs in and out of focus. Everything was working fine until I tried switching everything to (table / table-cell) in order to keep them all the Divs the same height in CSS. Now they still rotate out but one div remains visible with a reduced width off to the side of the stage. I get a sense that its position related but just can't figure out what's causing the issue.

Affected Page - https://www.harpercollege.edu/dev/blog-slider-test.php

JS Code:

$('.blog-posts').wrapInner('
');

// Calculate Conditions & Set Vars

// var playTimer = 9,
slideQty = $('.well').length,
  slideWidth = $('.well').width(),
  stageWidth = $('.blog-posts-stage').width(),
  contWidth = $('.blog-posts').width();

if ((slideQty * slideWidth) < contWidth) {
  $('.blog-posts-prev').addClass('blog-posts-prev-disabled').removeClass('blog-posts-prev');
  $('.blog-posts-next').addClass('blog-posts-next-disabled').removeClass('blog-posts-next');
} else {
  $('.blog-posts-prev-disabled').addClass('blog-posts-prev').removeClass('blog-posts-prev-disabled');
  $('.blog-posts-next-disabled').addClass('blog-posts-next').removeClass('blog-posts-next-disabled');
}

$(window).resize(function() {
  var slideQty = $('.well').length,
    slideWidth = $('.well').width(),
    stageWidth = $('.blog-posts-stage').width(),
    contWidth = $('.blog-posts').width();
  if ((slideQty * slideWidth) < contWidth) {
    $('.blog-posts-prev').addClass('blog-posts-prev-disabled').removeClass('blog-posts-prev');
    $('.blog-posts-next').addClass('blog-posts-next-disabled').removeClass('blog-posts-next');
  } else {
    $('.blog-posts-prev-disabled').addClass('blog-posts-prev').removeClass('blog-posts-prev-disabled');
    $('.blog-posts-next-disabled').addClass('blog-posts-next').removeClass('blog-posts-next-disabled');
  }
});

$('.blog-posts-next').on('click', function(event) {
  event.preventDefault();
  $('.blog-posts-stage').animate({
    left: -(slideWidth)
  }, 500, function() {
    $('.well:first').appendTo('.blog-posts-stage');
    $('.blog-posts-stage').css({
      left: '0px'
    });
  });
});

$('.blog-posts-prev').on('click', function(event) {
  event.preventDefault();
  $('.well:last').prependTo('.blog-posts-stage');
  $('.blog-posts-stage').css({
    left: -(slideWidth)
  });
  $('.blog-posts-stage').animate({
    left: '0px'
  }, 500, function() {});
});

function moveForward() {
  $('.blog-posts-stage').animate({
    left: -(slideWidth)
  }, 500, function() {
    $('.well:first').appendTo('.blog-posts-stage');
    $('.blog-posts-stage').css({
      left: '0px'
    });
  });
}
var timer = setInterval(moveForward, playTimer);

$('.blog-posts, .blog-posts-prev, .blog-posts-next').hover(function(ev) {
  // clearInterval(timer);
}, function(ev) {
  // timer = setInterval( moveForward, playTimer);
});

CSS Code:

Body:
You could just use a lightbox library and save yourself the effort, but if you really want to do this why not try flex?

.blog-posts-stage {
  display: flex;
  flex-direction: row;
  overflow: hidden;
}

.well-large {
  flex-shrink: 0;
}


问:
Use SQL Server trigger to insert into a backup table and link original to backup
I'm trying to implement the following logic in SQL Server:

every time data is inserted into MainTable, all this data should be also inserted into a backup table MainTable_BACKUP, and every row inserted into MainTable should have a foreign key BackupRecordId pointing to MainTable_BACKUP.

Can it be achieved using a trigger?

```<code>CREATE TRIGGER TRG_MainTable
ON MainTable
AFTER INSERT AS
BEGIN
    INSERT INTO MainTable_BACKUP
        SELECT *
        FROM INSERTED

    -- UPDATE INSERTED SET BackupRecordId = ??? somehow...
END
</code>```

答:
Yes you can.

Assuming that you have an identity column named BackupRecordId on you MainTable_BACKUP table, you can create an after insert trigger like this

```<code> Create Table MainTable
 (
    ID int IDENTITY(1, 1) PRIMARY KEY,
    Description NVARCHAR(50),
    BackupRecordId int
 )

 Create table MainTable_BACKUP
 (
    BackupRecordId int IDENTITY(1, 1) PRIMARY KEY,
    [Id] int,
    Description NVARCHAR(50)
 )

 CREATE TRIGGER TRG_MainTable
    ON MainTable
    AFTER INSERT AS
    BEGIN
        INSERT INTO MainTable_BACKUP([Id], Description)
        SELECT [Id], Description FROM INSERTED

        UPDATE MainTable
        SET BackupRecordId = MP.BackupRecordId
        FROM MainTable
        INNER JOIN inserted i on i.Id = MainTable.Id
        INNER JOIN MainTable_BACKUP MP ON MP.Id = MainTable.Id
    END
</code>```

You can try it with this:

```<code>insert into MainTable(Description)
values ('Testing')

select * from MainTable
select * from MainTable_BACKUP
</code>```

Body:
I'm trying to implement the following logic in SQL Server:

every time data is inserted into MainTable, all this data should be also inserted into a backup table MainTable_BACKUP, and every row inserted into MainTable should have a foreign key BackupRecordId pointing to MainTable_BACKUP.

Can it be achieved using a trigger?

CREATE TRIGGER TRG_MainTable
ON MainTable
AFTER INSERT AS
BEGIN
    INSERT INTO MainTable_BACKUP
        SELECT *
        FROM INSERTED

    -- UPDATE INSERTED SET BackupRecordId = ??? somehow...
END

Body:
Yes you can.

Assuming that you have an identity column named BackupRecordId on you MainTable_BACKUP table, you can create an after insert trigger like this

 Create Table MainTable
 (
    ID int IDENTITY(1, 1) PRIMARY KEY,
    Description NVARCHAR(50),
    BackupRecordId int
 )

 Create table MainTable_BACKUP
 (
    BackupRecordId int IDENTITY(1, 1) PRIMARY KEY,
    [Id] int,
    Description NVARCHAR(50)
 )

 CREATE TRIGGER TRG_MainTable
    ON MainTable
    AFTER INSERT AS
    BEGIN
        INSERT INTO MainTable_BACKUP([Id], Description)
        SELECT [Id], Description FROM INSERTED

        UPDATE MainTable
        SET BackupRecordId = MP.BackupRecordId
        FROM MainTable
        INNER JOIN inserted i on i.Id = MainTable.Id
        INNER JOIN MainTable_BACKUP MP ON MP.Id = MainTable.Id
    END

You can try it with this:

insert into MainTable(Description)
values ('Testing')

select * from MainTable
select * from MainTable_BACKUP


问:
How to import excel relationship matrix to Neo4j?
I want to import an excel file which is actually a relationship matrix nxn with several relationship types between the n elements.

```<code>id| name     | element1 | element2 | element3 ... n
1 | element1              1;2;3        1;5
2 | element2   1;2;3
3 | element3     1;5
...
</code>```

I saved the excel as CSV, which creates a lot of null cells (empty cells).

In Neo4j I tried:

```<code>load csv with headers from 'file:///test.csv' as line
WITH line where not line.ID is null
merge (c:element{id: toInteger(line.id),name: line.name})
</code>```

as a result, I receive no changes and records.

答:
Property names are case-sensitive in Neo4j Cypher.

Your file has column id but you are checking where not line.ID is null.
This will skip all the rows as there is no ID column in your CSV file.

Find below the modified version of your query for readability:

```<code>LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS line
WITH line
WHERE line.id IS NOT NULL
MERGE (c:element{id: toInteger(line.id),name: line.name})
</code>```

Body:
I want to import an excel file which is actually a relationship matrix nxn with several relationship types between the n elements.

id| name     | element1 | element2 | element3 ... n
1 | element1              1;2;3        1;5
2 | element2   1;2;3
3 | element3     1;5
...

I saved the excel as CSV, which creates a lot of null cells (empty cells).

In Neo4j I tried:

load csv with headers from 'file:///test.csv' as line
WITH line where not line.ID is null
merge (c:element{id: toInteger(line.id),name: line.name})

as a result, I receive no changes and records.

Body:
Property names are case-sensitive in Neo4j Cypher.

Your file has column id but you are checking where not line.ID is null.
This will skip all the rows as there is no ID column in your CSV file.

Find below the modified version of your query for readability:

LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS line
WITH line
WHERE line.id IS NOT NULL
MERGE (c:element{id: toInteger(line.id),name: line.name})


问:
My script when wrapped within a function doesn't yield any result
I've written a script in php to parse the link of each state located under the title High School Directory by State of a table from this url. My first function fetch_item_links() can extract those links in the right way. What I wish to do now is supply those urls within fetch_info() function so that it will parse the red colored link from the target page.

The second function also works flawlessly when I supply any individual url to test, as in this one.

However, when I try to run the whole script, I don't get any output. No error either.

This is my try so far:

```<code><?php
$url = 'http://www.directoryofschools.com/high-schools/US.html';
$prefix = 'http://www.directoryofschools.com';

function fetch_item_links($link,$base)
{
    $html_doc = new DOMDocument();
    @$html_doc->loadHtmlFile($link);
    $content_xpath = new DOMXPath($html_doc);
    $item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
    $packtBook = array();
    for ($i=0; $i <$item_row->length; $i++){
        $title = $item_row->item($i)->getAttribute('href') . "<br/>";
        $string = $base . str_replace("..", "", $title);
        $packtBook[] = $string;
    }
    return $packtBook;
}

function fetch_info($link)
{
    $html_doc = new DOMDocument();
    @$html_doc->loadHtmlFile($link);
    $content_xpath = new DOMXPath($html_doc);
    $item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
    for ($i=0; $i <$item_row->length; $i++){
        $title = $item_row->item($i)->getAttribute('href') . "<br/>";
        echo $title;
    }
}
$items = fetch_item_links($url,$prefix);
foreach($items as $file){
    fetch_info($file);
}
?>
</code>```

How can I make my script functional?

答:
You're appending
 to the URL in fetch_item_links, which means you won't be able to load it via loadHtmlFile(). Change the line to

```<code>$title = $item_row->item($i)->getAttribute('href');
</code>```

In fact, in both places, it might be better to remove the
, and only append it to the string when you're echoing it.

Body:
I've written a script in php to parse the link of each state located under the title High School Directory by State of a table from this url. My first function fetch_item_links() can extract those links in the right way. What I wish to do now is supply those urls within fetch_info() function so that it will parse the red colored link from the target page.

The second function also works flawlessly when I supply any individual url to test, as in this one.

However, when I try to run the whole script, I don't get any output. No error either.

This is my try so far:

<?php
$url = 'http://www.directoryofschools.com/high-schools/US.html';
$prefix = 'http://www.directoryofschools.com';

function fetch_item_links($link,$base)
{
    $html_doc = new DOMDocument();
    @$html_doc->loadHtmlFile($link);
    $content_xpath = new DOMXPath($html_doc);
    $item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
    $packtBook = array();
    for ($i=0; $i <$item_row->length; $i++){
        $title = $item_row->item($i)->getAttribute('href') . "
";
        $string = $base . str_replace("..", "", $title);
        $packtBook[] = $string;
    }
    return $packtBook;
}

function fetch_info($link)
{
    $html_doc = new DOMDocument();
    @$html_doc->loadHtmlFile($link);
    $content_xpath = new DOMXPath($html_doc);
    $item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
    for ($i=0; $i <$item_row->length; $i++){
        $title = $item_row->item($i)->getAttribute('href') . "
";
        echo $title;
    }
}
$items = fetch_item_links($url,$prefix);
foreach($items as $file){
    fetch_info($file);
}
?>

How can I make my script functional?

Body:
You're appending <br/> to the URL in fetch_item_links, which means you won't be able to load it via loadHtmlFile(). Change the line to

$title = $item_row->item($i)->getAttribute('href');

In fact, in both places, it might be better to remove the <br/>, and only append it to the string when you're echoing it.