问:
Available helpers / classes to parse ranges between two Time values
I've been attempting to solve an issue that I'm working on & not sure if there are any tools / helpers available which I'm missing to help me come to a solution / point me in the right direction.

I'm trying to read in two Time values, a start & an end. From there I need to create two new variables, one which contains the minutes which are inside a time range, and another with the minutes outside the range.

I've tried multiple approaches but can't seem to follow a correct path or find any useful methods.

```<code># Range to check between: (1pm - 7pm)(13 - 19)

@begin_time # Sun, 16 Feb 2020 05:11:33 UTC +00:00
@end_time   # Sun, 16 Feb 2020 19:43:42 UTC +00:00

#inital check to see if there are any values inside the range
@begin_time <= 13 && @end_time <= 17

# create an array containing all of the minutes between the two points, but not sure
# how I can compare these against the two times, as I don't believe you can create a static Time value
# total_range --> ["05:11", "05:12"... etc]
total_range = begin_time.strftime('%H:%M')..end_time.strftime('%H:%M').to_a

# could possibly generate the minutes in between the 1pm & 7pm values like above, compare the
# values - where the ones which exist = inside_values & the ones which don't = outside_values

# this would theoretically give me a basis of what I need, but doesn't look to be possible outside of the console
(@begin_time - CONST_ONE_PM_TIME) / 60
(CONST_SEVEN_PM_TIME - @end_time) / 60
</code>```

If anyone has any ideas or prompts on what I could potentially look into going forward, it would be greatly appreciated :)

Body:
I've been attempting to solve an issue that I'm working on & not sure if there are any tools / helpers available which I'm missing to help me come to a solution / point me in the right direction.

I'm trying to read in two Time values, a start & an end. From there I need to create two new variables, one which contains the minutes which are inside a time range, and another with the minutes outside the range.

I've tried multiple approaches but can't seem to follow a correct path or find any useful methods.

# Range to check between: (1pm - 7pm)(13 - 19)

@begin_time # Sun, 16 Feb 2020 05:11:33 UTC +00:00
@end_time   # Sun, 16 Feb 2020 19:43:42 UTC +00:00

#inital check to see if there are any values inside the range
@begin_time <= 13 && @end_time <= 17

# create an array containing all of the minutes between the two points, but not sure
# how I can compare these against the two times, as I don't believe you can create a static Time value
# total_range --> ["05:11", "05:12"... etc]
total_range = begin_time.strftime('%H:%M')..end_time.strftime('%H:%M').to_a

# could possibly generate the minutes in between the 1pm & 7pm values like above, compare the
# values - where the ones which exist = inside_values & the ones which don't = outside_values

# this would theoretically give me a basis of what I need, but doesn't look to be possible outside of the console
(@begin_time - CONST_ONE_PM_TIME) / 60
(CONST_SEVEN_PM_TIME - @end_time) / 60

If anyone has any ideas or prompts on what I could potentially look into going forward, it would be greatly appreciated :)

Body:
I will address what is effectively the same problem as given in the question, but is structured differently. It should not be difficult to modify the code below to suit the OP's requirements.

Data

Suppose we are given the following data.

require 'time'

SECS_PER_30_MINS = 1800
TIME_FMT = '%H:%M'

The time interval begins at '9:00' and ends at '16:59:59', covering 16 30-minute slots. Slot 0 is from '9:00:00' to '9:29:59', Slot 1 is from '9:30:00' to '9:59:59', and so on.

start_time = Time.strptime('9:00', TIME_FMT)
  #=> 2020-02-17 09:00:00 -0800

slots = 16.times.map { |i| (start_time + i*SECS_PER_30_MINS)...
  (start_time + (i+1)*SECS_PER_30_MINS) }
  #=> [2020-02-17 09:00:00 -0800...2020-02-17 09:30:00 -0800,
  #    2020-02-17 09:30:00 -0800...2020-02-17 10:00:00 -0800,
  #    2020-02-17 10:00:00 -0800...2020-02-17 10:30:00 -0800,
  #    ...
  #    2020-02-17 16:30:00 -0800...2020-02-17 17:00:00 -0800]

Notice that these are three-dot ranges, so the right endpoint of each range is not included in the range.

Suppose we have five events, with starting and ending times as follows:

event_times = [['08:00', '09:45'], ['08:30', '10:15'], ['12:34', '14:15'],
               ['11:30', '14:31'], ['15:30', '16:15']]

event_ranges = event_times.map do |s,e|
  Time.strptime(s, TIME_FMT)..Time.strptime(e, TIME_FMT)
end
  #=> [2020-02-17 08:00:00 -0800..2020-02-17 09:45:00 -0800,
  #    2020-02-17 08:30:00 -0800..2020-02-17 10:15:00 -0800,
  #    2020-02-17 12:34:00 -0800..2020-02-17 14:15:00 -0800,
  #    2020-02-17 11:30:00 -0800..2020-02-17 14:31:00 -0800,
  #    2020-02-17 15:30:00 -0800..2020-02-17 16:15:00 -0800]

Code

def slot_availability(slots, event_ranges)
  event_ranges.each_with_object([true]*slots.size) do |er,slot_avail|
  slots.each_with_index do |s,i|
    slot_avail[i] = false if s.cover?(er.begin) || s.cover?(er.end) ||
      er.cover?(s)
    end
  end
end

Example

For the arrays slots and event_ranges defined earlier we obtain:

slot_availability(slots, event_ranges)
  #     9:00-  9:30- 10:00- 10:30- 11:00- 11:30- 12:00- 12:30-
  #=> [false, false, false,  true,  true, false, false, false,
  #    false, false, false, false,  true, false, false,  true]
  #    13:00- 13:30- 14:00- 14:30- 15:00- 15:30- 16:00- 16:30-

Explanation

I defined a 16-element array slot_avail where slot_avail[i] equals true (else false) if slot i is not covered by any event. These values are all initialized to true.

The method then enumerates events, for each considering whether any part of the event falls within each slot i. There are three patterns in which an event could intrude on a slot:

eeeeeeee
    ssssssss

    eeeeeeee
ssssssss

eeeeeeeeeeee
  ssssssss

See Range#cover?.

Alternative to use of Time objects.

The use of Time objects actually buys very little here. The following is how slots and event_ranges might be defined without making use of Time objects. Each of these arrays contain ranges whose endpoints are numbers of minutes since the previous midnight. The method slot_availability is used unchanged.

We start by constructing a simple helper method.

def mins_since_midnight(str)
  str.split(':').map(&:to_i).zip([60, 1]).map { |a,x| a*x }.sum
end

mins_since_midnight('09:30')
  #=> 570

event_times = [['08:00', '09:45'], ['08:30', '10:15'], ['12:34', '14:15'],
               ['11:30', '14:31'], ['15:30', '16:15']]

event_ranges = event_times.map do |b,e|
  mins_since_midnight(b)..mins_since_midnight(e)
end
  #=> [480..585, 510..615, 754..855, 690..871, 930..975]

start_time = mins_since_midnight('9:00')
  #=> 540

slots = 16.times.map do |i|
  start_time + 30*i...start_time + 30*(i+1)
end
  #=> [540...570, 570...600, 600...630,..., 990...1020]

slot_availability(slots, event_ranges)
  #=> [false, false, false, true,  true, false, false, false,
  #    false, false, false, false, true, false, false, true]


来源: stackexchange

问:
SQL Server insert: using a static value to determine date value
I am inserting production orders into a SQL Server database with a stored procedure called via Microsoft PowerApps. Currently, the build date column is just using today's date as the build date. Attached below is a sample of records:

As you can see, all 10 of these orders have today's date as the set build date. However, I'd like to dynamically set this build date based upon the necessary output for the day. This will most likely be passed a variable to the stored procedure. For example - if the build output was 5 per day, rows 1-5 would have a build date of '02/17/2020' while the next 5 would have have a build date of '02/18/2020'.

This is simple enough since the number of orders is divisible by the build output. However, let's say the build output is 3 instead of 5. The first three orders would be '02/17/2020', the next three would be '02/18/2020', and the next three would be '02/19/2020'. This would leave one order to be set to '02/20/2020'. Then if I added more orders, it would stack upon each date filling each up to 3. Is there a way to do this via a stored procedure?

答:
You might need to do some adjustments but based on my understanding, this will do the trick ([Date] is the date column in your sample table above):

```<code>CREATE PROC yourProcName @pNUM AS INT = 1 --PARAMETER
AS
(
    DECLARE @pDate DATE;
    SET @pDate = COALESCE((SELECT TOP 1 CONVERT(DATE, MAX([Date])), GETDATE()) FROM yourDestTable); --SETTING THE DATE AS MAX DATE ALREADY EXISTS IN THE TABLE. IF NOTHING IS THERE, WE'LL USE TODAY
    DECLARE @pLead INT = COALESCE((SELECT TOP 1 COUNT(*) FROM yourDestTable WHERE [Date] = @pDate), 0);--SEE HOW MANY RECORDS IN THE DATABASE EXIST WITH THE DATE WE DEFINED
    WITH cte
    AS
    (
        SELECT *,
        FLOOR((
                ROW_NUMBER() OVER(ORDER BY @pDate) -
                0.001)/@pNUM) AS RN -- SEPARATING RECORDS USING ROW_NUMBER DIVIDED BY DEFINED NUMBER OF PRODS PER DAY. USING FLOOR AND MINUS A SMALL AMOUNT TO ROUND IT RIGHT
        FROM yourSourceTable
    )
    INSERT INTO yourDestTable
    SELECT
        C.*,
        DATEADD(DAY, LEAD(C.RN, @pLead), @pDate) AS [Date] --PUSHING THE NUMBER BASED ON ROWS ALREADY EXISTED WITH THE MAX_DATE
    INTO yourDestTable
    FROM cte AS C
)
</code>```

You might want to use MOD in CTE based on your usecase. But the idea should work. Then call it like this EXEC yourProcName <number of transactionsday>

ContentLicense: CC BY-SA 4.0

Body:
You might need to do some adjustments but based on my understanding, this will do the trick ([Date] is the date column in your sample table above):

CREATE PROC yourProcName @pNUM AS INT = 1 --PARAMETER
AS
(
    DECLARE @pDate DATE;
    SET @pDate = COALESCE((SELECT TOP 1 CONVERT(DATE, MAX([Date])), GETDATE()) FROM yourDestTable); --SETTING THE DATE AS MAX DATE ALREADY EXISTS IN THE TABLE. IF NOTHING IS THERE, WE'LL USE TODAY
    DECLARE @pLead INT = COALESCE((SELECT TOP 1 COUNT(*) FROM yourDestTable WHERE [Date] = @pDate), 0);--SEE HOW MANY RECORDS IN THE DATABASE EXIST WITH THE DATE WE DEFINED
    WITH cte
    AS
    (
        SELECT *,
        FLOOR((
                ROW_NUMBER() OVER(ORDER BY @pDate) -
                0.001)/@pNUM) AS RN -- SEPARATING RECORDS USING ROW_NUMBER DIVIDED BY DEFINED NUMBER OF PRODS PER DAY. USING FLOOR AND MINUS A SMALL AMOUNT TO ROUND IT RIGHT
        FROM yourSourceTable
    )
    INSERT INTO yourDestTable
    SELECT
        C.*,
        DATEADD(DAY, LEAD(C.RN, @pLead), @pDate) AS [Date] --PUSHING THE NUMBER BASED ON ROWS ALREADY EXISTED WITH THE MAX_DATE
    INTO yourDestTable
    FROM cte AS C
)

You might want to use MOD in CTE based on your usecase. But the idea should work. Then call it like this EXEC yourProcName <number of transactionsday>


问:
Range based for loop: Iterate over vector extended with one element
I want to achieve more less the equivalent to this Python code in C++ (but more memory efficient):

```<code>a = [1, 5, 3]
additional = 6
for elem in [additional] + a:
    print(elem) # prints: 6 1 5 3

# alternative without creating the additional vector:
import itertools
for elem in itertools.chain([additional], a):
    print(elem)
</code>```

The only way that I know to do this in C++ is:

```<code>#include <iostream>
#include <vector>

int main() {
        std::vector<int> a = {1, 5, 3};
        int additional = 6;

        for (int i = 0; i < a.size() + 1; ++i) {
                int cur_elem;
                if (i == 0) {
                        cur_elem = additional;
                } else {
                        cur_elem = a[i-1];
                }
                std::cout << cur_elem << std::endl;
        }
}
</code>```

Is there a way to do this with a range based for loop? I found the Boost join operator but it seems to use only iterables, so I need to create an extra vector (like in the Python example).

Ideally, the iteration would be without creating the joined object in the memory and with algorithms of the standard library.

答:
It can be done using the upcoming ranges feature.

Here's an example using Eric Niebler's range-v3 library:

```<code>#include <iostream>
#include <vector>

#include <range/v3/view/concat.hpp>
#include <range/v3/view/single.hpp>

int main() {
    std::vector<int> a = {1, 5, 3};
    int additional = 6;
    for (auto i : ranges::concat_view(ranges::single_view{additional}, a)) {
        std::cout << i;
    }
}
</code>```

See it live!

by using views, all iterator operations are lazy, and no extra memory is used (e.g.: no extra vectors/arrays are created)

Or, without the for loop:

```<code>ranges::copy(ranges::concat_view(ranges::single_view{additional}, a), ranges::make_ostream_joiner(std::cout, ","));
</code>```

See it live!

(Honestly, I like the for version better, though)

Standard-compliant solution

There's a small issue with the solution above: concat_view did not make it into C++20. If you want a strictly compliant solution, you may want to create your own version, or use join_view instead:

```<code>#include <iostream>
#include <vector>

#include <ranges>

int main() {
    std::vector<int> a = {1, 5, 3};
    int additional = 6;

    std::vector v{{additional}, a};

    for(int i : std::ranges::join_view{v}) {
        std::cout << i;
    }
}
</code>```

Body:
I want to achieve more less the equivalent to this Python code in C++ (but more memory efficient):

a = [1, 5, 3]
additional = 6
for elem in [additional] + a:
    print(elem) # prints: 6 1 5 3

# alternative without creating the additional vector:
import itertools
for elem in itertools.chain([additional], a):
    print(elem)

The only way that I know to do this in C++ is:

#include <iostream>
#include <vector>

int main() {
        std::vector<int> a = {1, 5, 3};
        int additional = 6;

        for (int i = 0; i < a.size() + 1; ++i) {
                int cur_elem;
                if (i == 0) {
                        cur_elem = additional;
                } else {
                        cur_elem = a[i-1];
                }
                std::cout << cur_elem << std::endl;
        }
}

Is there a way to do this with a range based for loop? I found the Boost join operator but it seems to use only iterables, so I need to create an extra vector (like in the Python example).

Ideally, the iteration would be without creating the joined object in the memory and with algorithms of the standard library.

Body:
It can be done using the upcoming ranges feature.

Here's an example using Eric Niebler's range-v3 library:

#include <iostream>
#include <vector>

#include <range/v3/view/concat.hpp>
#include <range/v3/view/single.hpp>

int main() {
    std::vector<int> a = {1, 5, 3};
    int additional = 6;
    for (auto i : ranges::concat_view(ranges::single_view{additional}, a)) {
        std::cout << i;
    }
}

See it live!

by using views, all iterator operations are lazy, and no extra memory is used (e.g.: no extra vectors/arrays are created)

Or, without the for loop:

ranges::copy(ranges::concat_view(ranges::single_view{additional}, a), ranges::make_ostream_joiner(std::cout, ","));

See it live!

(Honestly, I like the for version better, though)

Standard-compliant solution

There's a small issue with the solution above: concat_view did not make it into C++20. If you want a strictly compliant solution, you may want to create your own version, or use join_view instead:

#include <iostream>
#include <vector>

#include <ranges>

int main() {
    std::vector<int> a = {1, 5, 3};
    int additional = 6;

    std::vector v{{additional}, a};

    for(int i : std::ranges::join_view{v}) {
        std::cout << i;
    }
}


问:
How to fix Crystal Report Thai language problem
I have develop web application and use Crystal Report.

The problem occur when i use Thai language.

Thai symbol cannot read and its replace with square symbol.

The result have no problem when use CrystalReportViewer on window application (figure 1).

But the problem occur on web site (figure 2), when user request a report, i send the report back with pdf file format.

figure 1: Expecated Result

figure 2: Problem Result

The code look like below.

```<code>rptExternalTransferReport rptH = new rptExternalTransferReport();
rptH.FileName = Server.MapPath("/Reports/rptExternalTransferReport.rpt");
rptH.Load();
rptH.SetDataSource([datatable]);
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf");
</code>```

How to fixed this problem.

Help me please.

Edit 17-May, 2011:
Look like the problem is occur when i export to pdf file.
Because i try use CrystalReportViewer, it have no problem.
But when export to pdf, the problem occurred.

PS. Sorry for my english writing :)

答: Did you try to install Thai language on your machine?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have develop web application and use Crystal Report.

The problem occur when i use Thai language.

Thai symbol cannot read and its replace with square symbol.

The result have no problem when use CrystalReportViewer on window application (figure 1).

But the problem occur on web site (figure 2), when user request a report, i send the report back with pdf file format.

figure 1: Expecated Result

figure 2: Problem Result

The code look like below.

rptExternalTransferReport rptH = new rptExternalTransferReport();
rptH.FileName = Server.MapPath("/Reports/rptExternalTransferReport.rpt");
rptH.Load();
rptH.SetDataSource([datatable]);
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf");

How to fixed this problem.

Help me please.

Edit 17-May, 2011:
Look like the problem is occur when i export to pdf file.
Because i try use CrystalReportViewer, it have no problem.
But when export to pdf, the problem occurred.

PS. Sorry for my english writing :)


问:
ASP Net Core multiple environment publishing
Coming from the .NET MVC world, I am confused on how .NET Core deals with multi-environment deployments. (Dev, Test, Production)

The tech used here are Bamboo (Build Server) + Octopus Deploy (CD).

.NET Core appears to be using appsettings instead, and web.config is only used for IIS Hosting.

Upon reading some guides, which suggests to add an Environment Variable "ASPNETCORE_ENVIRONMENT" to the project to define the environment currently in.

This is the command I used to build in Bamboo.
dotnet publish -c Test ${bamboo.build.working.directory}\HelloWorld.sln

Questions...
1. I have appsettings.json, appsettings.Test.json, appsettings.Production.json.
   It looks like the app knows which appsettings file to read from, based on the
   ASPNETCORE_ENVIRONMENT value.

How can I tell Octopus to use the correct file based on the environment I am deploying to?

答:
Having a variable and multiple config files packaged up make things overly complicated, especially if you're using Octopus Deploy.

The only reason for having multiple .environment.json files is because these are probably held in source control and they have their values already set - so environment variables are probably all coming from the source code, rather than the release manager. Otherwise, they'd be identical files and Octopus would still be transforming them (which makes them redundant)

My advice would be to move to a single file, and move the variables into Octopus Deploy. Remove the ASPNETCORE_ENVIRONMENT and you only need one file appSettings.json, which can be transformed during deployment to whatever environment.

ASP.NET Core Web Applications - Octopus Deploy Documentation

Hope this helps


问:
How can I move a single line of text up by 10px or 15px using CSS?
I have a single line of text in my footer of my html/php website, next to it is a twitter button. The problem is visually it doesn't look right as the button is out of line with the line of text. I have tried evrything I can think of from line-hight to padding, margins and just plan height but nothing is getting the line of text where I want it to be. I have tried minus values to like 3em and -3em.

Can anyone think of a way to force the line up by roughly 10px - 15px?

答:
Try</p>

```<code>position: relative;
display: inline-block;
bottom: 15px;
</code>```

Body:
Try

position: relative;
display: inline-block;
bottom: 15px;


问:
Activating a Worksheet from a Close Window functions as expected but not from an Exit option in an Add-In menubar
I have a Code Workbook and several Data workbooks with multiple worksheets.  I need to be able to Activate a particular worksheet when closing a Data workbook.  If I use the 'X' in the upper right corner of the Data workbook, the worksheet changes.  If I use the Exit option in an Add-In Menu bar, even though the program runs through the same BeforeClose code, it will not Activate the correct worksheet.

The following code is in a code module in the CodeBook.xlsm file:

```<code>Option Explicit

Sub Auto_Open()
    'Establish a special menu
    MenuBars(xlWorksheet).Menus.Add Caption:="O&ptions"
    'Create Menu Items
    MenuBars(xlWorksheet).Menus("Options").MenuItems.Add Caption:="Open CodeBook1.xlsm", OnAction:="Open_File"
    MenuBars(xlWorksheet).Menus("Options").MenuItems.Add Caption:="Exit", OnAction:="AutoClose"

End Sub

Sub Open_File()
    Dim sPath As String
    sPath = ThisWorkbook.Path
    Workbooks.Open sPath & "\DataBook1.xlsm"
End Sub

Public Sub AutoClose()
    'See if an Event workbook or the Main workbood called the subroutine
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then
        ActiveWorkbook.Save
        MsgBox "Before ActiveWorkbook.Close"
        ActiveWorkbook.Close
        MsgBox "Back from ActiveWorkbook.Close"
        Exit Sub
    End If
End Sub

</code>```

The following code is in ThisWorkbook in the DataBook1.xlsm which has a Sheet1 and Sheet2:

```<code>Public Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sBk As String
    Dim cApp As Object
    Set cApp = Application
    sBk = ThisWorkbook.Name
    ThisWorkbook.Save
    Worksheets("Sheet2").Activate
    MsgBox "Codebook Workbook Before Close  After Activate Sheet2" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
    Worksheets("Sheet1").Activate
    MsgBox "Codebook Workbook Before Close After Activate Sheet1" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
'    Cancel = True
End Sub

Private Sub Workbook_Open()
   Worksheets("Sheet1").Activate
End Sub
</code>```

To make it easier to test, uncomment the Cancel = True in the DataBook ThisWorkbook code.

答:
My testing would suggest that worksheets can't be "activated" from within ThisWorkbook, that is Workbook_BeforeClose etc. The code runs, but nothing happens.

You might be able to overcome this by executing the activate(s) in a normal code module (which sits in the data worksheet) first.

For example, in a (normal) code module in DataBook1.xlsm add:

```<code>Option Explicit

Public Sub SwapSheets()
    Worksheets("Sheet2").Activate
    MsgBox "Codebook Workbook Before Close  After Activate Sheet2" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
    Worksheets("Sheet1").Activate
    MsgBox "Codebook Workbook Before Close After Activate Sheet1" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
End Sub
</code>```

Then modify your AutoClose in CodeBook.xlsm to call the above first ... before executing the other code.

```<code>Public Sub AutoClose()
    'See if an Event workbook or the Main workbood called the subroutine
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then

        ' do the activates here first
        ActiveWorkbook.Application.Run ("'" & ActiveWorkbook.Name & "'!SwapSheets")

        ActiveWorkbook.Save
        ActiveWorkbook.Close
        Exit Sub
    End If
End Sub
</code>```

Body:
I have a Code Workbook and several Data workbooks with multiple worksheets.  I need to be able to Activate a particular worksheet when closing a Data workbook.  If I use the 'X' in the upper right corner of the Data workbook, the worksheet changes.  If I use the Exit option in an Add-In Menu bar, even though the program runs through the same BeforeClose code, it will not Activate the correct worksheet.

The following code is in a code module in the CodeBook.xlsm file:

Option Explicit

Sub Auto_Open()
    'Establish a special menu
    MenuBars(xlWorksheet).Menus.Add Caption:="O&ptions"
    'Create Menu Items
    MenuBars(xlWorksheet).Menus("Options").MenuItems.Add Caption:="Open CodeBook1.xlsm", OnAction:="Open_File"
    MenuBars(xlWorksheet).Menus("Options").MenuItems.Add Caption:="Exit", OnAction:="AutoClose"

End Sub

Sub Open_File()
    Dim sPath As String
    sPath = ThisWorkbook.Path
    Workbooks.Open sPath & "\DataBook1.xlsm"
End Sub

Public Sub AutoClose()
    'See if an Event workbook or the Main workbood called the subroutine
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then
        ActiveWorkbook.Save
        MsgBox "Before ActiveWorkbook.Close"
        ActiveWorkbook.Close
        MsgBox "Back from ActiveWorkbook.Close"
        Exit Sub
    End If
End Sub

The following code is in ThisWorkbook in the DataBook1.xlsm which has a Sheet1 and Sheet2:

Public Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sBk As String
    Dim cApp As Object
    Set cApp = Application
    sBk = ThisWorkbook.Name
    ThisWorkbook.Save
    Worksheets("Sheet2").Activate
    MsgBox "Codebook Workbook Before Close  After Activate Sheet2" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
    Worksheets("Sheet1").Activate
    MsgBox "Codebook Workbook Before Close After Activate Sheet1" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
'    Cancel = True
End Sub

Private Sub Workbook_Open()
   Worksheets("Sheet1").Activate
End Sub

To make it easier to test, uncomment the Cancel = True in the DataBook ThisWorkbook code.

Body:
My testing would suggest that worksheets can't be "activated" from within ThisWorkbook, that is Workbook_BeforeClose etc. The code runs, but nothing happens.

You might be able to overcome this by executing the activate(s) in a normal code module (which sits in the data worksheet) first.

For example, in a (normal) code module in DataBook1.xlsm add:

Option Explicit

Public Sub SwapSheets()
    Worksheets("Sheet2").Activate
    MsgBox "Codebook Workbook Before Close  After Activate Sheet2" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
    Worksheets("Sheet1").Activate
    MsgBox "Codebook Workbook Before Close After Activate Sheet1" & vbNewLine & _
        "ActiveWindow " & ActiveWindow.Caption & vbNewLine & _
        "ThisWorkbook " & ThisWorkbook.Name & vbNewLine & _
        "ActiveWorkbook " & ActiveWorkbook.Name & vbNewLine & _
        "ActiveSheet " & ActiveSheet.Name & vbNewLine & _
        "Display Alerts " & Application.DisplayAlerts & vbNewLine & _
        "Events Enabled " & Application.EnableEvents & vbNewLine & _
        "Screen Updating " & Application.ScreenUpdating
End Sub

Then modify your AutoClose in CodeBook.xlsm to call the above first ... before executing the other code.

Public Sub AutoClose()
    'See if an Event workbook or the Main workbood called the subroutine
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then

        ' do the activates here first
        ActiveWorkbook.Application.Run ("'" & ActiveWorkbook.Name & "'!SwapSheets")

        ActiveWorkbook.Save
        ActiveWorkbook.Close
        Exit Sub
    End If
End Sub


问:
How do I prevent this infinite loop
When I run the following code, sometimes it will exit successfully and sometimes it will enter an infinite loop if highestNum is equal to 255. I understand that this happens because of rollover when 255 gets incremented and becomes 0. I understand why this is happening but I would like advice on stopping this. Should I put an if statement at the end to check if i is equal to the max number and then break at the end? this seems like bad style and something that is easy to forget to fix if i increased the size of the variables.</p>

```<code>    // delete all the files
    for (unsigned char i = 0; i <= highestNum; i++){
        rc = snprintf(formatString, sizeof(formatString), "x%u", i);
        if (rc < 0){
            perror("snprintf in delete");
        }
        rc = unlinkat(directoryFD, formatString, 0);
        if (rc == 0){
            printf("file unlinked\n");
        }
    }
</code>```

答:
Use instead of the type unsigned char the type unsigned int.:)
Otherwise when i is equal to the maximum value for the type that is to 255  (UCHAR_MAX is equal to 255) then the next value after increment of i will be again 0 and you will get an infinite loop.

So any value of the variable highestNum that is equal to or greater than UCHAR_MAX results in infinite loop.

Title: How do I prevent this infinite loop

Body:
When I run the following code, sometimes it will exit successfully and sometimes it will enter an infinite loop if highestNum is equal to 255. I understand that this happens because of rollover when 255 gets incremented and becomes 0. I understand why this is happening but I would like advice on stopping this. Should I put an if statement at the end to check if i is equal to the max number and then break at the end? this seems like bad style and something that is easy to forget to fix if i increased the size of the variables.

    // delete all the files
    for (unsigned char i = 0; i <= highestNum; i++){
        rc = snprintf(formatString, sizeof(formatString), "x%u", i);
        if (rc < 0){
            perror("snprintf in delete");
        }
        rc = unlinkat(directoryFD, formatString, 0);
        if (rc == 0){
            printf("file unlinked\n");
        }
    }


问:
Prolog, building list with conditional clauses
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

```<code>goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).
</code>```

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

答:
If I understand correctly, then what you need is a predicate like include/3:

```<code>include(:Goal, +List1, ?List2)
    Filter elements for which Goal succeeds. True if List2 contains
    those elements Xi of List1 for which call(Goal, Xi) succeeds.
</code>```

Usage example:

```<code>?- include(number, [a(b), 2, _, 1.2, C, '1'], L).
L = [2, 1.2].
</code>```

Now your homework becomes "how to implement include/3". Once you have implemented your version of include/3 you can check if it matches SWI's version by looking at its source code: listing(include).

Body:
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

Body:
If I understand correctly, then what you need is a predicate like include/3:

include(:Goal, +List1, ?List2)
    Filter elements for which Goal succeeds. True if List2 contains
    those elements Xi of List1 for which call(Goal, Xi) succeeds.

Usage example:

?- include(number, [a(b), 2, _, 1.2, C, '1'], L).
L = [2, 1.2].

Now your homework becomes "how to implement include/3". Once you have implemented your version of include/3 you can check if it matches SWI's version by looking at its source code: listing(include).


答:
One way of avoiding this can be declaring i as an int, and then casting it to a char in the loop where it is used.

```<code>for (unsigned int i = 0; i <= highestNum; i++){
    rc = snprintf(formatString, sizeof(formatString), "x%u", (unsigned char) i);
    if (rc < 0){
        perror("snprintf in delete");
    }
    rc = unlinkat(directoryFD, formatString, 0);
    if (rc == 0){
        printf("file unlinked\n");
    }
}
</code>```

Title: How do I prevent this infinite loop

Body:
One way of avoiding this can be declaring i as an int, and then casting it to a char in the loop where it is used.

for (unsigned int i = 0; i <= highestNum; i++){
    rc = snprintf(formatString, sizeof(formatString), "x%u", (unsigned char) i);
    if (rc < 0){
        perror("snprintf in delete");
    }
    rc = unlinkat(directoryFD, formatString, 0);
    if (rc == 0){
        printf("file unlinked\n");
    }
}


问:
PolyUtil.decode Throwing StringIndexOutOfBoundsException
When using Google Maps PolyUtil.decode it gives me this error java.lang.StringIndexOutOfBoundsException: length=60; index=60 at java.lang.String.charAt(Native Method) at com.google.maps.android.PolyUtil.decode(PolyUtil.java:464)
When I trace the error it gives me the PolyUtil.class which then takes me to this particular line

```<code>do{
  b = encodedPath.charAt(index++) - 63 - 1;
  result += b << shift;
  shift += 5;
} while(b >= 31);
</code>```

But so far this error is only thrown for a particular encoded string. When I decode another encoded string of the same length in characters or one that is longer or shorter in length it doesn't throw the error. I've even tested the string that gives the error using Google's Interactive Polyline Decoder Tool and it shows up properly. Any reason why this error is being thrown happen?

答:
The issue is the double back slashes "\\". Just replace them with a single back slash "\", before decoding.

As followed:

```<code>String newEncodedString = encodedString.replace("\\\\","\\");
PolyUtil.decode(newEncodedString);
</code>```

Body:
When using Google Maps PolyUtil.decode it gives me this error java.lang.StringIndexOutOfBoundsException: length=60; index=60 at java.lang.String.charAt(Native Method) at com.google.maps.android.PolyUtil.decode(PolyUtil.java:464)
When I trace the error it gives me the PolyUtil.class which then takes me to this particular line

do{
  b = encodedPath.charAt(index++) - 63 - 1;
  result += b << shift;
  shift += 5;
} while(b >= 31);

But so far this error is only thrown for a particular encoded string. When I decode another encoded string of the same length in characters or one that is longer or shorter in length it doesn't throw the error. I've even tested the string that gives the error using Google's Interactive Polyline Decoder Tool and it shows up properly. Any reason why this error is being thrown happen?

Body:
The issue is the double back slashes "\\". Just replace them with a single back slash "\", before decoding.

As followed:

String newEncodedString = encodedString.replace("\\\\","\\");
PolyUtil.decode(newEncodedString);


问:
How to use scapy to send GTPv2 message?
I'm using scapy (https://github.com/secdev/scapy) to send gtpv2 Echo Request message as below:

```<code>from scapy.contrib.gtp_v2 import GTPV2EchoRequest as GTPV2EchoRequest
from scapy.contrib.gtp_v2 import IE_RecoveryRestart as IE_RecoveryRestart
from scapy.contrib.gtp_v2 import GTPV2Command as GTPV2Command
ie = IE_RecoveryRestart(ietype='Recovery Restart', restart_counter=17, CR_flag=0, instance=0)
gtp = IP(src="10.64.13.28", dst="10.71.33.131")/UDP(sport=2123, dport=2123) / GTPHeader(seq=12345) / GTPV2EchoRequest() / GTPV2Command() / ie
ans, unans = sr1(gtp,timeout=2)
</code>```

But, I see malformed packet on wireshark.:

wireshark-snapshot

Any idea what am I missing here?

答:
Following code worked:</p>

```<code>from scapy.contrib.gtp_v2 import GTPHeader as GTPHeader
from scapy.contrib.gtp_v2 import GTPV2EchoRequest as GTPV2EchoRequest
from scapy.contrib.gtp_v2 import IE_RecoveryRestart as IE_RecoveryRestart
ie = IE_RecoveryRestart(ietype='Recovery Restart', length=1, restart_counter=17, CR_flag=0, instance=0)
gtp = Ether()/IP(dst="10.15.11.93")/UDP(sport=2123, dport=2123) / GTPHeader(seq=12345, length=9, P=0) / GTPV2EchoRequest(IE_list=[ie])
ans, unans = srp1(gtp,timeout=2,iface='eth0')
</code>```

Title: How to use scapy to send GTPv2 message?

Body:
I'm using scapy (https://github.com/secdev/scapy) to send gtpv2 Echo Request message as below:

from scapy.contrib.gtp_v2 import GTPV2EchoRequest as GTPV2EchoRequest
from scapy.contrib.gtp_v2 import IE_RecoveryRestart as IE_RecoveryRestart
from scapy.contrib.gtp_v2 import GTPV2Command as GTPV2Command
ie = IE_RecoveryRestart(ietype='Recovery Restart', restart_counter=17, CR_flag=0, instance=0)
gtp = IP(src="10.64.13.28", dst="10.71.33.131")/UDP(sport=2123, dport=2123) / GTPHeader(seq=12345) / GTPV2EchoRequest() / GTPV2Command() / ie
ans, unans = sr1(gtp,timeout=2)

But, I see malformed packet on wireshark.:

wireshark-snapshot

Any idea what am I missing here?

Body:
Following code worked:

from scapy.contrib.gtp_v2 import GTPHeader as GTPHeader
from scapy.contrib.gtp_v2 import GTPV2EchoRequest as GTPV2EchoRequest
from scapy.contrib.gtp_v2 import IE_RecoveryRestart as IE_RecoveryRestart
ie = IE_RecoveryRestart(ietype='Recovery Restart', length=1, restart_counter=17, CR_flag=0, instance=0)
gtp = Ether()/IP(dst="10.15.11.93")/UDP(sport=2123, dport=2123) / GTPHeader(seq=12345, length=9, P=0) / GTPV2EchoRequest(IE_list=[ie])
ans, unans = srp1(gtp,timeout=2,iface='eth0')


问:
Set Kestrel Unix socket file permissions in ASP.NET Core?
Kestrel can be configured to use a Unix socket to communicate with a reverse proxy (i.e. nginx) for a slight performance advantage. However, the socket file is deleted and recreated each time the kestrel server stops/starts, resetting the socket's permissions and depending on system configuration, blocking nginx from accessing the socket.

What is a simple and reliable method to ensure Kestrel's Unix socket permissions are opened up on creation?

答:
The following sample Program.Main demonstrates the use of chmod via P/Invoke. This solution allows for use of managed sockets on Windows and switches to libuv when ListenUnixSocket is configured via appsettings.json, and in that case, calls chmod directly on startup to establish socket permissions.

Code for Chmod class largely lifted from: https://silvercircle.github.io/2018/08/26/serving-net-core-kestrel-linux-unix-sockets/

UseLibuv requires dependency on Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv via NuGet.

```<code>namespace UnixSocketDemo
{
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Threading.Tasks;
    using static System.String;

    public class Program
    {
        private static string _unixSocket = null;

        public static async Task Main(string[] args)
        {
            var webHost = BuildWebHost(args);
            await webHost.StartAsync();
            if (!IsNullOrWhiteSpace(_unixSocket))
                Chmod.Set(_unixSocket);

            await webHost.WaitForShutdownAsync();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var builder = WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) => config.SetBasePath(Directory.GetCurrentDirectory()))
                .UseStartup<Startup>();

            var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            var kestrelConfig = config.GetSection("Kestrel");
            if (kestrelConfig.Exists())
            {
                _unixSocket = kestrelConfig.GetValue<string>("ListenUnixSocket");
                if (!IsNullOrWhiteSpace(_unixSocket))
                    builder.UseLibuv();

                builder.ConfigureKestrel((hostingContext, serverOptions) =>
                {
                    serverOptions.Configure(kestrelConfig);
                    if (!IsNullOrWhiteSpace(_unixSocket))
                        serverOptions.ListenUnixSocket(_unixSocket);
                });
            }

            return builder.Build();
        }

        private static class Chmod
        {
            [DllImport("libc", EntryPoint="chmod", SetLastError = true)]
            [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "interop")]
            private static extern int chmod(string pathname, int mode);

            // user permissions
            const int S_IRUSR = 0x100;
            const int S_IWUSR = 0x80;
            const int S_IXUSR = 0x40;

            // group permission
            const int S_IRGRP = 0x20;
            const int S_IWGRP = 0x10;
            const int S_IXGRP = 0x8;

            // other permissions
            const int S_IROTH = 0x4;
            const int S_IWOTH = 0x2;
            const int S_IXOTH = 0x1;

            public static void Set(string filename)
            {
                const int _0755 =
                    S_IRUSR | S_IXUSR | S_IWUSR
                    | S_IRGRP | S_IXGRP | S_IWGRP
                    | S_IROTH | S_IXOTH | S_IWOTH;

                if (0 != chmod(Path.GetFullPath(filename), (int)_0755))
                    throw new Exception("Could not set Unix socket permissions");
            }
        }
    }
}
</code>```

Body:
The following sample Program.Main demonstrates the use of chmod via P/Invoke. This solution allows for use of managed sockets on Windows and switches to libuv when ListenUnixSocket is configured via appsettings.json, and in that case, calls chmod directly on startup to establish socket permissions.

Code for Chmod class largely lifted from: https://silvercircle.github.io/2018/08/26/serving-net-core-kestrel-linux-unix-sockets/

UseLibuv requires dependency on Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv via NuGet.

namespace UnixSocketDemo
{
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Threading.Tasks;
    using static System.String;

    public class Program
    {
        private static string _unixSocket = null;

        public static async Task Main(string[] args)
        {
            var webHost = BuildWebHost(args);
            await webHost.StartAsync();
            if (!IsNullOrWhiteSpace(_unixSocket))
                Chmod.Set(_unixSocket);

            await webHost.WaitForShutdownAsync();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var builder = WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) => config.SetBasePath(Directory.GetCurrentDirectory()))
                .UseStartup<Startup>();

            var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            var kestrelConfig = config.GetSection("Kestrel");
            if (kestrelConfig.Exists())
            {
                _unixSocket = kestrelConfig.GetValue<string>("ListenUnixSocket");
                if (!IsNullOrWhiteSpace(_unixSocket))
                    builder.UseLibuv();

                builder.ConfigureKestrel((hostingContext, serverOptions) =>
                {
                    serverOptions.Configure(kestrelConfig);
                    if (!IsNullOrWhiteSpace(_unixSocket))
                        serverOptions.ListenUnixSocket(_unixSocket);
                });
            }

            return builder.Build();
        }

        private static class Chmod
        {
            [DllImport("libc", EntryPoint="chmod", SetLastError = true)]
            [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "interop")]
            private static extern int chmod(string pathname, int mode);

            // user permissions
            const int S_IRUSR = 0x100;
            const int S_IWUSR = 0x80;
            const int S_IXUSR = 0x40;

            // group permission
            const int S_IRGRP = 0x20;
            const int S_IWGRP = 0x10;
            const int S_IXGRP = 0x8;

            // other permissions
            const int S_IROTH = 0x4;
            const int S_IWOTH = 0x2;
            const int S_IXOTH = 0x1;

            public static void Set(string filename)
            {
                const int _0755 =
                    S_IRUSR | S_IXUSR | S_IWUSR
                    | S_IRGRP | S_IXGRP | S_IWGRP
                    | S_IROTH | S_IXOTH | S_IWOTH;

                if (0 != chmod(Path.GetFullPath(filename), (int)_0755))
                    throw new Exception("Could not set Unix socket permissions");
            }
        }
    }
}


问:
Can I load JS ES6+ modules in modern Swift’s JavaScriptCore?
Using JavaScriptCore, I would like to integrate part of a modern Javascript codebase into a Swift 5.x program for ios/ipados 13. The JS code uses ES6+ features extensively. For example: async/await, static imports (import * as something from “something.js”), and dynamic imports (`await loadedModule = import(“something.js”);

Based on this post from 2018, it seems as though import statements weren’t implemented properly at that point: How to import modules in Swift's JavaScriptCore?

(I don’t think that it’s appropriate to resurrect that post since at this point a lot has changed.)

Since that time, has JavaScriptCore integrated these features? From my understanding, if they work in the Safari browser, then they should also work in standalone JavaScriptCore (or is that wrong to assume)? I don’t think it would be practical to use babel or webpack to convert my code.

If it’s possible, how do I load this sort of JavaScript from Swift?

EDIT:

I still get
JS Exception: SyntaxError: Unexpected token '*'. import call expects exactly one argument.

when I try the following:

import * as mod from "./mod.js";

答: The answer is "no," but I can use Babel to transpile files with static imports / exports into code containing requires, and also implement my own version of require in Swift to simulate what I want.


问:
Stenciljs: Carousel third-party library destroyed when I change scope: 'true' for shadow: 'true'
I've a carousel based on the Swiperjs third-party library. The problem is that when I use scope: true, I have no problem and it works fine, however, when I try to configure the component with shadow: true, it is destroyed and nothing works. I am using the library as follows:

...
import  Swiper, { SwiperOptions }  from 'swiper';
...

@Component({
  tag: 'my-swiper-slider',
  styleUrl: './styles.css',
  assetsDirs: ['assets'],
  shadow: true,
})
export class Carousel {
@Prop() options: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 40,
    autoplay: false,
    loop: false,
    autoHeight: true,
    breakpoints: {
      640: {
        slidesPerView: 5,
        spaceBetween: 20,
      },
      768: {
        slidesPerView: 5,
        spaceBetween: 40,
      },
      1024: {
        slidesPerView: 5,
        spaceBetween: 50,
      },
    }
  }
 private setSwiper() {
    this.swiper = new Swiper('.swiper-container', this.options);
  }

  componentDidLoad() {
    this.setSwiper();
  }

  render() {

    return (
      <Host class={{"container": true}}>

        <PrevBtn
          goBack={this.goBack.bind(this)} />

            <slot></slot>

        <NextBtn
          goForward={this.goForward.bind(this)} />

      </Host>
    );
  }
}
```

For some reason, when I configure the component as "shadow: true", it cannot access stencil or is what I think.

答:
When you enable shadow, all child elements of the component will be moved into its shadow DOM and therefore be hidden as implementation detail. That means that you won't be able to find your container with the .swiper-container query selector anymore.

However, the Swiper constructor can also take an HTML element instead of a query selector, so you can use ref on the container element instead:

```<code>@Component({ tag: 'my-swiper-slider', shadow: true })
export class Carousel {
  @Prop() options: SwiperOptions;

  @State() swiper?: Swiper;
  @State() swiperContainerRef?: HTMLDivElement;

  componentDidLoad() {
    if (this.swiperContainerRef) {
      this.swiper = new Swiper(this.swiperContainerRef, this.options);
    }
  }

  render() {
    return (
      <Host>
        <div ref={el => this.swiperContainerRef = el)} />
      </Host>
    );
  }
}
</code>```

The container ref should always already be available in the componentDidLoad life-cycle hook, but you can also use requestAnimationFrame to wait for it to become available.

Body:
I've a carousel based on the Swiperjs third-party library. The problem is that when I use scope: true, I have no problem and it works fine, however, when I try to configure the component with shadow: true, it is destroyed and nothing works. I am using the library as follows:

...
import  Swiper, { SwiperOptions }  from 'swiper';
...

@Component({
  tag: 'my-swiper-slider',
  styleUrl: './styles.css',
  assetsDirs: ['assets'],
  shadow: true,
})
export class Carousel {
@Prop() options: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 40,
    autoplay: false,
    loop: false,
    autoHeight: true,
    breakpoints: {
      640: {
        slidesPerView: 5,
        spaceBetween: 20,
      },
      768: {
        slidesPerView: 5,
        spaceBetween: 40,
      },
      1024: {
        slidesPerView: 5,
        spaceBetween: 50,
      },
    }
  }
 private setSwiper() {
    this.swiper = new Swiper('.swiper-container', this.options);
  }

  componentDidLoad() {
    this.setSwiper();
  }

  render() {

    return (
      <Host class={{"container": true}}>

        <PrevBtn
          goBack={this.goBack.bind(this)} />

            <slot></slot>

        <NextBtn
          goForward={this.goForward.bind(this)} />

      </Host>
    );
  }
}

For some reason, when I configure the component as "shadow: true", it cannot access stencil or is what I think.

Body:
When you enable shadow, all child elements of the component will be moved into its shadow DOM and therefore be hidden as implementation detail. That means that you won't be able to find your container with the .swiper-container query selector anymore.

However, the Swiper constructor can also take an HTML element instead of a query selector, so you can use ref on the container element instead:

@Component({ tag: 'my-swiper-slider', shadow: true })
export class Carousel {
  @Prop() options: SwiperOptions;

  @State() swiper?: Swiper;
  @State() swiperContainerRef?: HTMLDivElement;

  componentDidLoad() {
    if (this.swiperContainerRef) {
      this.swiper = new Swiper(this.swiperContainerRef, this.options);
    }
  }

  render() {
    return (
      <Host>
        <div ref={el => this.swiperContainerRef = el)} />
      </Host>
    );
  }
}

The container ref should always already be available in the componentDidLoad life-cycle hook, but you can also use requestAnimationFrame to wait for it to become available.


问:
Do I have to know what the AID of a card is for card emulation with Android HCE?
I merely want to emulate a transit card with an Android application using HCE. I'm confused about the AID of the card. Do I have to know what the AID of the card is?

According to Host-based Card Emulation document:

If you are emulating cards for an existing NFC reader infrastructure,
  the AIDs that those readers are looking for are typically well-known
  and publicly registered (for example, the AIDs of payment networks
  such as Visa and MasterCard).

So, what is the point?

P.S. I don't think the AID of my card is well-known. Even if it is, how do I know what it is?

答:
AIDs for Visa, Master card and other known companies are registered. You can find the AIDs in the below Wikipedia link

https://en.wikipedia.org/wiki/EMV

AIDs for the Visa from the above link

Visa - A0000000031010, A0000000032010, A0000000032020, A0000000038010


问:
Regex in mongoid search
I'm a little confused about how to achieve a regex with text searches in mongoid

I index with my contacts model like so:

```<code>index(FirstName: "text", LastName: "text")
</code>```

In my search action I have:

```<code>search = '/.*' + search_string + '.*/'
@contacts.collection.find( { '$text': { '$search': search } }, "collation" => { "locale" => "en_US" } )
</code>```

So when I pass a string, like "Joh" and I expect it to return case-insensitive results that will include contacts with names like "Majoh", "Majohboo" and "John" because of the regex I added around the search string.

What am I doing wrong and what should my query be like to achieve that?
If I am unable to achieve that with a text type index, then what would you recommend I replace my indexing with?

答:
You seem to be confusing regular expression queries with full text search.

To perform a regular expression query, pass the regular expression:

```<code>irb(main):002:0> Band.create!(name: 'hello')
=> #<Band _id: 5e4b39e5026d7c7b6fcfc1ad, name: "hello", description: nil>
irb(main):003:0> Band.collection.find(name: /el/).first
=> {"_id"=>BSON::ObjectId('5e4b39e5026d7c7b6fcfc1ad'), "name"=>"hello"}
irb(main):004:0> Band.collection.find(name: /EL/).first
=> nil
irb(main):006:0> Band.collection.find(name: /EL/i).first
=> {"_id"=>BSON::ObjectId('5e4b39e5026d7c7b6fcfc1ad'), "name"=>"hello"}
</code>```

This does not use $text operator.

To perform full text search, see https://docs.mongodb.com/mongoid/master/tutorials/mongoid-queries/#full-text-search. This does not use regular expressions.

You need to understand the difference between full text search and regular expression queries. Each has its uses. Developers are generally more familiar with regular expressions than with full text search, so perhaps you would benefit from reading up on how full text search works. Full text search does not work for arbitrary word fragments because it works on the basis of lexemes. Regular expressions do not reduce to word lexemes and thus are a poor choice for many natural language queries.

If you want to query with regular expressions, you can do that on multiple fields by combining multiple criteria (one per field) with $or. If you want full text search, regular expressions are not applicable, define a full text search index containing all of the fields you wish to search and use the $text operator.

Title: Regex in mongoid search

Body:
I'm a little confused about how to achieve a regex with text searches in mongoid

I index with my contacts model like so:

index(FirstName: "text", LastName: "text")

In my search action I have:

search = '/.*' + search_string + '.*/'
@contacts.collection.find( { '$text': { '$search': search } }, "collation" => { "locale" => "en_US" } )

So when I pass a string, like "Joh" and I expect it to return case-insensitive results that will include contacts with names like "Majoh", "Majohboo" and "John" because of the regex I added around the search string.

What am I doing wrong and what should my query be like to achieve that?
If I am unable to achieve that with a text type index, then what would you recommend I replace my indexing with?

Body:
You seem to be confusing regular expression queries with full text search.

To perform a regular expression query, pass the regular expression:

irb(main):002:0> Band.create!(name: 'hello')
=> #<Band _id: 5e4b39e5026d7c7b6fcfc1ad, name: "hello", description: nil>
irb(main):003:0> Band.collection.find(name: /el/).first
=> {"_id"=>BSON::ObjectId('5e4b39e5026d7c7b6fcfc1ad'), "name"=>"hello"}
irb(main):004:0> Band.collection.find(name: /EL/).first
=> nil
irb(main):006:0> Band.collection.find(name: /EL/i).first
=> {"_id"=>BSON::ObjectId('5e4b39e5026d7c7b6fcfc1ad'), "name"=>"hello"}

This does not use $text operator.

To perform full text search, see https://docs.mongodb.com/mongoid/master/tutorials/mongoid-queries/#full-text-search. This does not use regular expressions.

You need to understand the difference between full text search and regular expression queries. Each has its uses. Developers are generally more familiar with regular expressions than with full text search, so perhaps you would benefit from reading up on how full text search works. Full text search does not work for arbitrary word fragments because it works on the basis of lexemes. Regular expressions do not reduce to word lexemes and thus are a poor choice for many natural language queries.

If you want to query with regular expressions, you can do that on multiple fields by combining multiple criteria (one per field) with $or. If you want full text search, regular expressions are not applicable, define a full text search index containing all of the fields you wish to search and use the $text operator.


问:
copy whole html table to clipboard javascript
I have write javascript to select the table but I want to now automaticaly copy it after the click of the button.Please help me.My javascript is like this.</p>

```<code>function selectElementContents(el) {
            var body = document.body, range, sel;
            if (document.createRange && window.getSelection) {
                range = document.createRange();
                sel = window.getSelection();
                sel.removeAllRanges();
                try {
                    range.selectNodeContents(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                } catch (e) {
                    range.selectNode(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                }
            } else if (body.createTextRange) {
                range = body.createTextRange();
                range.moveToElementText(el);
                range.select();
                range.execCommand('Copy');

            }
        }
</code>```

答:
This has worked for me, it is not only restricted to table, but it can even select and copy to clipboard all elements inside Node specified with id.

I have tested in Mac Chrome as well as windows chrome.

Usescase : Copy Signature created by Signature Generator based on JS

Demo :

The Company Name

 Firstname Lastname    Designation

youreamil@xyz.com

<input type="button" onclick="selectElementContents( document.getElementById('signature_container') );" value="Copy to Clipboard">

```

Body:
I have write javascript to select the table but I want to now automaticaly copy it after the click of the button.Please help me.My javascript is like this.

function selectElementContents(el) {
            var body = document.body, range, sel;
            if (document.createRange && window.getSelection) {
                range = document.createRange();
                sel = window.getSelection();
                sel.removeAllRanges();
                try {
                    range.selectNodeContents(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                } catch (e) {
                    range.selectNode(el);
                    sel.addRange(range);
                    document.execCommand('Copy');
                }
            } else if (body.createTextRange) {
                range = body.createTextRange();
                range.moveToElementText(el);
                range.select();
                range.execCommand('Copy');

            }
        }

Body:
This has worked for me, it is not only restricted to table, but it can even select and copy to clipboard all elements inside Node specified with id.

I have tested in Mac Chrome as well as windows chrome.

Usescase : Copy Signature created by Signature Generator based on JS

Demo :

<div id="signature_container">
  <p id="company_name" style="margin-top: 4px; margin-bottom: 0px; color: #522e64; font-weight: 700; font-size: 16px; letter-spacing: 1px; border-bottom: solid 2px #522e64; width:250px; padding-bottom: 3px;">The Company Name</p>
  <p style="margin-top: 4px; margin-bottom: 0px; color: #00706a; font-weight: 700; font-size: 15px;"> <span id="first_name_output_2"></span>Firstname<span id="last_name_output_2"> Lastname</span>&nbsp;&nbsp;&nbsp;&nbsp;<span id="designation_output_2" style="color: #000000; font-weight: 500; font-size: 15px;">Designation</span></p>
  <p style="margin-top: 0px; margin-bottom: 0px; color: #625469; font-weight: normal; font-size: 15px; letter-spacing: 0.6px;">youreamil@xyz.com<span id="email_output_2"></span>&nbsp;&nbsp;&nbsp;</p>
</div>
<br><br>
<input type="button" onclick="selectElementContents( document.getElementById('signature_container') );" value="Copy to Clipboard">

<script>
  function selectElementContents(el) {
    var body = document.body,
      range, sel;
    if (document.createRange && window.getSelection) {
      range = document.createRange();
      sel = window.getSelection();
      sel.removeAllRanges();
      range.selectNodeContents(el);
      sel.addRange(range);
    }
    document.execCommand("Copy");
  }
</script>


答:
```<code>display: block;
margin-bottom: 15px;
</code>```

Title: How can I move a single line of text up by 10px or 15px using CSS?

Body:
I have a single line of text in my footer of my html/php website, next to it is a twitter button. The problem is visually it doesn't look right as the button is out of line with the line of text. I have tried evrything I can think of from line-hight to padding, margins and just plan height but nothing is getting the line of text where I want it to be. I have tried minus values to like 3em and -3em.

Can anyone think of a way to force the line up by roughly 10px - 15px?

Body:
display: block;
margin-bottom: 15px;


问:
How to host ASP.NET Core 2.0 (Kestrel) with Unix domain socket behind a nginx proxy?
I am current using ASP.NET Core 2.0 behind nginx through HTTP requests in Ubuntu 16.

And I'd like to switch to Unix domain socket.

In my Program.cs I have:

var host = default(IWebHost);
var builder = new WebHostBuilder()
    .UseKestrel(opt =>
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && settings.Config.ListenUnixSocket)
        {
            opt.ListenUnixSocket("/tmp/api.sock");
        }
    })
    .Configure(app =>
    {
        app.Map("/health", b => b.Run(async context =>
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            await context.Response.WriteAsync("Ok");
        }));
    });

if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || !settings.Config.ListenUnixSocket)
{
    host = builder.UseUrls("http://0.0.0.0:5501").Build();
}
else
{
    host = builder.Build();
}

host.Run();
```
<p>And, at <strong>Nginx</strong>:</p>
<pre class="lang-txt prettyprint-override"><code>location /health {
  #proxy_pass http://127.0.0.1:5501;
  proxy_pass http://unix:/tmp/api.sock:/;
}
</code>```

Running it using the default TCP socket works, but switching to Unix domain sockets, I got a 502 error.

Do I need any specific module at nginx? What I am doing wrong?

答:
@Apolineo correctly identified that the Unix socket's permissions need to be opened up to allow other users to connect to the socket.

However, a better solution than manually setting the permissions is to do it programmatically from Main immediately after the socket is created.

Example solution in this answer.

Body:
I am current using ASP.NET Core 2.0 behind nginx through HTTP requests in Ubuntu 16.

And I'd like to switch to Unix domain socket.

In my Program.cs I have:

var host = default(IWebHost);
var builder = new WebHostBuilder()
    .UseKestrel(opt =>
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && settings.Config.ListenUnixSocket)
        {
            opt.ListenUnixSocket("/tmp/api.sock");
        }
    })
    .Configure(app =>
    {
        app.Map("/health", b => b.Run(async context =>
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            await context.Response.WriteAsync("Ok");
        }));
    });

if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || !settings.Config.ListenUnixSocket)
{
    host = builder.UseUrls("http://0.0.0.0:5501").Build();
}
else
{
    host = builder.Build();
}

host.Run();

And, at Nginx:

location /health {
  #proxy_pass http://127.0.0.1:5501;
  proxy_pass http://unix:/tmp/api.sock:/;
}

Running it using the default TCP socket works, but switching to Unix domain sockets, I got a 502 error.

Do I need any specific module at nginx? What I am doing wrong?


问:
AWS Elastic Beanstalk ERROR: InvalidParameterValueError
While using command - eb deploy

I am getting below error. YAML is fine syntax wise

ERROR: InvalidParameterValueError - Each option setting in configuration file .ebextensions/environ-
v1.config in application version app-4c59-191023_045651 must be a map. Update each option setting in the configuration file.

.config file in .ebextensions folder which is in root of project

 option_settings:
   aws:elasticbeanstalk:application:environment:
     PORT:8081
     NODE_ENV:development
   aws:autoscaling:launchconfiguration:
     SecurityGroups:launch-123

答:
have you tried double quotes in .config file like

```<code>"aws:elasticbeanstalk:application:environment":
</code>```

instead of

```<code>aws:elasticbeanstalk:application:environment:
</code>```

and, respectively,

```<code>"aws:autoscaling:launchconfiguration":
</code>```

instead of

```<code>aws:autoscaling:launchconfiguration:
</code>```

Body:
have you tried double quotes in .config file like

"aws:elasticbeanstalk:application:environment":

instead of

aws:elasticbeanstalk:application:environment:

and, respectively,

"aws:autoscaling:launchconfiguration":

instead of

aws:autoscaling:launchconfiguration:


问:
generate_series() equivalent in snowflake
I'm trying to find the snowflake equivalent of generate_series() (the PostgreSQL syntax).</p>

```<code>SELECT generate_series(timestamp '2017-11-01', CURRENT_DATE, '1 day')
</code>```

答:
I had a similar problem and found an approach, which avoids the issue of a generator requiring a constant value by using a session variable in addition to the already great answers here. This is closest to the requirement of the OP to my mind.</p>

```<code>-- set parameter to be used as generator "constant" including the start day
set num_days =  (Select datediff(day, TO_DATE('2017-11-01','YYYY-MM-DD'), current_date()+1));
-- use parameter in bcrowell's answer now
select
  dateadd(
    day,
    '-' || row_number() over (order by null),
    dateadd(day, '+1', current_date())
  ) as date
from table (generator(rowcount => ($num_days)));
-- clean up previously set variable
unset num_days;
</code>```

Body:
I'm trying to find the snowflake equivalent of generate_series() (the PostgreSQL syntax).

SELECT generate_series(timestamp '2017-11-01', CURRENT_DATE, '1 day')

Body:
I had a similar problem and found an approach, which avoids the issue of a generator requiring a constant value by using a session variable in addition to the already great answers here. This is closest to the requirement of the OP to my mind.

-- set parameter to be used as generator "constant" including the start day
set num_days =  (Select datediff(day, TO_DATE('2017-11-01','YYYY-MM-DD'), current_date()+1));
-- use parameter in bcrowell's answer now
select
  dateadd(
    day,
    '-' || row_number() over (order by null),
    dateadd(day, '+1', current_date())
  ) as date
from table (generator(rowcount => ($num_days)));
-- clean up previously set variable
unset num_days;


问:
ASP.NET Core 3.1 is getting an empty body
The code below, which is summarized for better understanding, works perfectly with LOCALHOST, however, when I put it in IIS, the body of the request always arrives EMPTY. Can someone help me?

Client application code:

```<code>  login(userName: string, password: string): Observable<User> {

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    return this.http.post(`${environment.API_URL}/profiles/login`,
      { userName, password }, { headers }
    ).pipe(
      tap((currentUser: User) => {
        this.updateUser(currentUser)
          .then(
            () => {
              console.log('currentUser login stored: ', AppSettings.currentUser);
            },
            error => console.error('Error storing currentUser login', error)
          );
        return AppSettings.currentUser;
      }),
    );
  }
</code>```

ASP.NET Core 3.1 application code on the server:

```<code>    [Route("api/[controller]")]
    [ApiController]
    public class ProfilesController : ControllerBase
    {
        [HttpPost("login")]
        public async Task<ActionResult> Login(LoginRequest request)
        {
            try
            {
                using (var Reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var sb = new StringBuilder();

                    sb.AppendFormat("ContentType: {0}\n", Request.ContentType);
                    sb.AppendFormat("Request: {0}\n", Request.ToString());
                    sb.AppendFormat("ContentLength: {0}\n", Request.ContentLength.ToString());
                    if (Request.IsHttps)
                        sb.AppendFormat("{0}\n", "HTTPS!");

                    var headers = String.Empty;
                    foreach (var key in Request.Headers)
                        headers += key.Key + "=" + key.Value + Environment.NewLine;
                    sb.AppendFormat("Headers: \n{0}\n", headers);

                    sb.AppendFormat("QueryString: {0}\n", Request.QueryString);

                    var text = await Reader.ReadToEndAsync();
                    sb.AppendFormat("Body: {0}\n", text);
                    return Ok(sb.ToString());
                }
                return Ok("OK");
            }
            catch (System.Exception ex)
            {
                return Unauthorized($"{ex.Message}: {ex.StackTrace}");
            }
        }
    }
</code>```

Request result:

```<code>ContentType: application/json
Request: Microsoft.AspNetCore.Http.DefaultHttpRequest
ContentLength: 79
Headers:
Accept=*/*
Accept-Encoding=gzip, deflate, br
Cache-Control=no-cache
Connection=keep-alive
Content-Length=79
Content-Type=application/json
Host=loja.online
User-Agent=PostmanRuntime/7.22.0
Postman-Token=121f1927-c340-492f-a98b-0d6586ff32d8

QueryString:
Body:
</code>```

Using POSTMAN the same thing happens!

答:
Try Specifying the source:

```<code>    public async Task<ActionResult> Login([FromBody] LoginRequest request) //Added [FromBody]
</code>```

Just for Further Details

Body:
The code below, which is summarized for better understanding, works perfectly with LOCALHOST, however, when I put it in IIS, the body of the request always arrives EMPTY. Can someone help me?

Client application code:

  login(userName: string, password: string): Observable<User> {

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    return this.http.post(`${environment.API_URL}/profiles/login`,
      { userName, password }, { headers }
    ).pipe(
      tap((currentUser: User) => {
        this.updateUser(currentUser)
          .then(
            () => {
              console.log('currentUser login stored: ', AppSettings.currentUser);
            },
            error => console.error('Error storing currentUser login', error)
          );
        return AppSettings.currentUser;
      }),
    );
  }

ASP.NET Core 3.1 application code on the server:

    [Route("api/[controller]")]
    [ApiController]
    public class ProfilesController : ControllerBase
    {
        [HttpPost("login")]
        public async Task<ActionResult> Login(LoginRequest request)
        {
            try
            {
                using (var Reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var sb = new StringBuilder();

                    sb.AppendFormat("ContentType: {0}\n", Request.ContentType);
                    sb.AppendFormat("Request: {0}\n", Request.ToString());
                    sb.AppendFormat("ContentLength: {0}\n", Request.ContentLength.ToString());
                    if (Request.IsHttps)
                        sb.AppendFormat("{0}\n", "HTTPS!");

                    var headers = String.Empty;
                    foreach (var key in Request.Headers)
                        headers += key.Key + "=" + key.Value + Environment.NewLine;
                    sb.AppendFormat("Headers: \n{0}\n", headers);

                    sb.AppendFormat("QueryString: {0}\n", Request.QueryString);

                    var text = await Reader.ReadToEndAsync();
                    sb.AppendFormat("Body: {0}\n", text);
                    return Ok(sb.ToString());
                }
                return Ok("OK");
            }
            catch (System.Exception ex)
            {
                return Unauthorized($"{ex.Message}: {ex.StackTrace}");
            }
        }
    }

Request result:

ContentType: application/json
Request: Microsoft.AspNetCore.Http.DefaultHttpRequest
ContentLength: 79
Headers:
Accept=*/*
Accept-Encoding=gzip, deflate, br
Cache-Control=no-cache
Connection=keep-alive
Content-Length=79
Content-Type=application/json
Host=loja.online
User-Agent=PostmanRuntime/7.22.0
Postman-Token=121f1927-c340-492f-a98b-0d6586ff32d8

QueryString:
Body:

Using POSTMAN the same thing happens!

Body:
Try Specifying the source:

    public async Task<ActionResult> Login([FromBody] LoginRequest request) //Added [FromBody]

Just for Further Details


问:
Eclipse not recognizing Gradle dependencies
I am new to Gradle and I was trying this tutorial https://spring.io/guides/gs/rest-service/
I was able to compile the jar with the required dependencies and run it.
However, I find it annoying that the libraries are not recognized by the IDE.

Is there anyway to do it?

答:
If you are on mac do what dpr mentioned. That is add the following in build.gradle:

```<code>apply plugin: "eclipse"
</code>```

Then run the following:

```<code>gradle cleanEclipse eclipse
</code>```

Body:
If you are on mac do what dpr mentioned. That is add the following in build.gradle:

apply plugin: "eclipse"

Then run the following:

gradle cleanEclipse eclipse


问:
How to share array memory between JavaScriptCore and Swift?
I am trying to write a Swift program that runs JS via JavaScriptCore. I wish to share memory between both parts of my program such that the JS writes to a typed array buffer created in Swift, and Swift reads and writes to it afterwards. This will be a sort of command buffer.

For example, here is some pseudocode that approximately represents what I'm planning to do:

```<code>// js
let buf;
let i = 0;
setup() {
   buf = new Uint8Array(mem.alloc(N_BYTES));
}

frame() {
   i = 0;
   buf[i++] = some_command_enum;
}

// swift
func alloc(bytes : Int) -> the_memory {
    // allocate bytes uints and save the memory here
    // save a reference to the memory here
    // return the memory to use in JS
}
</code>```

The problem is that whenever I try actually adding the implementation to alloc, JS reports via exception that the function is undefined, meaning that something is off with the way I'm doing things. Non-returning functions are fine, so I have that down.

This is my faulty implementation (please see the comments):

// swift
@objc protocol JSMemoryExports: JSExport {
    static func alloc(_ byte_count: Int) -> JSObjectRef
    static func free(_ memory: JSObjectRef)
}

class JSMemory: NSObject, JSMemoryExports {
                                           // What is the correct return type?
    class func alloc(_ byte_count: Int) -> JSObjectRef {
        // temp
        let jsContext = JS_Controller.js.ctx!

        print("BYTE_COUNT", byte_count)

        // allocating a typed array
        let arr = JSObjectMakeTypedArray(jsContext.jsGlobalContextRef!, kJSTypedArrayTypeUint8Array, byte_count, nil)

        // just testing here to see how I'd write to this buffer (Note: is this the fastest way, or is all this memory binding slow?:
        // getting the raw bytes
        let ptr = JSObjectGetTypedArrayBytesPtr(jsContext.jsGlobalContextRef!, arr, nil)
        //let buf = JSObjectGetTypedArrayBuffer(jsContext.jsGlobalContextRef, arr, nil)
        let u8Ptr = ptr!.bindMemory(to: UInt8.self, capacity: byte_count)
        //u8Ptr[0] = 5
        return arr!
    }
}

...

jsContext["mem"] = JSMemory.self

```

<pre class="lang-js prettyprint-override"><code>// js
const buf = new Uint8Array(mem.alloc(8)) // JS Exception: TypeError: mem.alloc is not a function. (In 'mem.alloc(8)', 'mem.alloc' is undefined)

</code>```

I've seen variants of function binding that uses some sort of @convention attribute. Am I meant to use that instead?

What is the correct thing to do?

答:
The documentation isn't very helpful unless you piece together a lot of information from separate sources. The seemingly working solution involves using parts of the older C API that are callable in Swift, unsafe pointers, and making sure the return values of the bound functions are JSValue?s. That makes sense since JavaScript functions all return an object, null, or undefined. An optional type mirrors this behavior.

Here is my work-in-progress code for anyone who might need some leads:

Just for an update, I've figured out how to mix the old C API with the new more limited Swift-specific APIs. I haven't yet made sure I'm not leaking memory, but it looks like I've found what I needed, hopefully.

In case you ever wanted to know:

@objc protocol JSMemoryExports: JSExport {
    // note that I'm returning an optional
    static func Uint8ArrayMake(_ count : JSValue) -> JSValue?
}

class JSMemory: NSObject, JSMemoryExports {
    class func UInt8ArrayMake(_ count : JSValue) -> JSValue? {
        guard !count.isUndefined && !count.isNull else {
            return nil
        }

        let ref : JSValueRef = JSObjectMakeTypedArray(
            JS_Controller.js.ctx.jsGlobalContextRef!,
            kJSTypedArrayTypeUint8Array,
            Int(count.toInt32()),
            nil
        )!

        // if you want to modify the data
        // let ptr = JSObjectGetTypedArrayBytesPtr(
        //    JS_Controller.js.ctx.jsGlobalContextRef!, ref, nil
        // )

        return JSValue(jsValueRef: ref, in: JS_Controller.js.ctx)
    }
}
```

Here are a couple helpful references:

pointers in Swift

manual memory management in Swift

Body:
I am trying to write a Swift program that runs JS via JavaScriptCore. I wish to share memory between both parts of my program such that the JS writes to a typed array buffer created in Swift, and Swift reads and writes to it afterwards. This will be a sort of command buffer.

For example, here is some pseudocode that approximately represents what I'm planning to do:

// js
let buf;
let i = 0;
setup() {
   buf = new Uint8Array(mem.alloc(N_BYTES));
}

frame() {
   i = 0;
   buf[i++] = some_command_enum;
}

// swift
func alloc(bytes : Int) -> the_memory {
    // allocate bytes uints and save the memory here
    // save a reference to the memory here
    // return the memory to use in JS
}

The problem is that whenever I try actually adding the implementation to alloc, JS reports via exception that the function is undefined, meaning that something is off with the way I'm doing things. Non-returning functions are fine, so I have that down.

This is my faulty implementation (please see the comments):

// swift
@objc protocol JSMemoryExports: JSExport {
    static func alloc(_ byte_count: Int) -> JSObjectRef
    static func free(_ memory: JSObjectRef)
}

class JSMemory: NSObject, JSMemoryExports {
                                           // What is the correct return type?
    class func alloc(_ byte_count: Int) -> JSObjectRef {
        // temp
        let jsContext = JS_Controller.js.ctx!

        print("BYTE_COUNT", byte_count)

        // allocating a typed array
        let arr = JSObjectMakeTypedArray(jsContext.jsGlobalContextRef!, kJSTypedArrayTypeUint8Array, byte_count, nil)

        // just testing here to see how I'd write to this buffer (Note: is this the fastest way, or is all this memory binding slow?:
        // getting the raw bytes
        let ptr = JSObjectGetTypedArrayBytesPtr(jsContext.jsGlobalContextRef!, arr, nil)
        //let buf = JSObjectGetTypedArrayBuffer(jsContext.jsGlobalContextRef, arr, nil)
        let u8Ptr = ptr!.bindMemory(to: UInt8.self, capacity: byte_count)
        //u8Ptr[0] = 5
        return arr!
    }
}

...

jsContext["mem"] = JSMemory.self

// js
const buf = new Uint8Array(mem.alloc(8)) // JS Exception: TypeError: mem.alloc is not a function. (In 'mem.alloc(8)', 'mem.alloc' is undefined)

I've seen variants of function binding that uses some sort of @convention attribute. Am I meant to use that instead?

What is the correct thing to do?

Body:
The documentation isn't very helpful unless you piece together a lot of information from separate sources. The seemingly working solution involves using parts of the older C API that are callable in Swift, unsafe pointers, and making sure the return values of the bound functions are JSValue?s. That makes sense since JavaScript functions all return an object, null, or undefined. An optional type mirrors this behavior.

Here is my work-in-progress code for anyone who might need some leads:

Just for an update, I've figured out how to mix the old C API with the new more limited Swift-specific APIs. I haven't yet made sure I'm not leaking memory, but it looks like I've found what I needed, hopefully.

In case you ever wanted to know:

@objc protocol JSMemoryExports: JSExport {
    // note that I'm returning an optional
    static func Uint8ArrayMake(_ count : JSValue) -> JSValue?
}

class JSMemory: NSObject, JSMemoryExports {
    class func UInt8ArrayMake(_ count : JSValue) -> JSValue? {
        guard !count.isUndefined && !count.isNull else {
            return nil
        }

        let ref : JSValueRef = JSObjectMakeTypedArray(
            JS_Controller.js.ctx.jsGlobalContextRef!,
            kJSTypedArrayTypeUint8Array,
            Int(count.toInt32()),
            nil
        )!

        // if you want to modify the data
        // let ptr = JSObjectGetTypedArrayBytesPtr(
        //    JS_Controller.js.ctx.jsGlobalContextRef!, ref, nil
        // )

        return JSValue(jsValueRef: ref, in: JS_Controller.js.ctx)
    }
}

Here are a couple helpful references:

pointers in Swift

manual memory management in Swift


问:
The Command "File.BatchNewTeamProject" is not available in VSTS 2010
I am trying to automate the creation of team projects using a command built into VS 2010 called File.BatchNewTeamProject using a project settings file as an argument, and executing this as a process silently in the background from my c# win app. I am aware of a requirement that Team Explorer has to be open and connected to TFS before this command can run, however, when I start a process with devenv.exe, a fresh instance of visual studio pops up with Team Explorer not connected by default. How can I solve this problem?</p>

答:
Just posted this project on Codeplex: http://tfsprojprovisioner.codeplex.com/

Includes an assembly that hides BatchNewTeamProject behind a simple programmatic interface, and a sample desktop app that you can use to create and provision new Team Projects.  Must be run on a computer that has VS 2010 installed, and by a user that has permissions to create new projects.  But it doesn't require you to interact with VS directly, at all.

ContentLicense: CC BY-SA 2.5


问:
Split text file after specific line in python
I'm trying to write a code to read Fresco files and plot the results. Fresco produces one big file that looks something like this

```<code>theta  sigma
1        0.1
2        0.1
3        0.2
...
END
some text...
theta   sigma
1        0.3
2        0.2
...
END
more data...
</code>```

I want to produce a new file after every 'END' to analyze the data separately. I tried some of the solutions proposed to other answers like

```<code>with open('fort.16', 'r') as infile, open('output_fort.16', 'w') as outfile:
copy= False
for line in infile:
    if line.strip() == '# legend':
        copy = True
        continue
    elif line.strip()=='End':
        copy = False
    elif copy:
        outfile.write(line)
</code>```

but this is not what i need.
Im fairly new to python so any help is much appreciated.

答:
I managed to solve this with a nested generator:

```<code>import re

SECTION_START = re.compile(r'^\s*theta\s+sigma\s*$')
SECTION_END = re.compile(r'^\s*END\s*$')

def fresco_iter(stream):
    def inner(stream):
        # Yields each line until an end marker is found (or EOF)
        for line in stream:
            if line and not SECTION_END.match(line):
                yield line
                continue
            break

    # Find a start marker, then break off into a nested iterator
    for line in stream:
        if line:
            if SECTION_START.match(line):
                yield inner(stream)
            continue
        break
</code>```

The fresco_iter method returns a generator that can be for-looped over. It returns 1 generator per section of theta sigma pairs.

```<code>>>> with open('fort.16', 'r') as fh:
...     print(list(fresco_iter(fh)))
[<generator object fresco_iter.<locals>.inner at 0x7fbc6da15678>,
 <generator object fresco_iter.<locals>.inner at 0x7fbc6da15570>]
</code>```

So to make use of this, you create your own nested loop to process the nested generators.

```<code>filename = 'fort.16'

with open(filename, 'r') as fh:
    for nested_iter in fresco_iter(fh):
        print('--- start')
        for line in nested_iter:
            print(line.rstrip())
        print('--- end')
</code>```

would output...

```<code>--- start
1        0.1
2        0.1
3        0.2
--- end
--- start
1        0.3
2        0.2
--- end
</code>```

This strategy only ever holds 1 line of your input file in memory at a time, so would work for any size file, on even the smallest device... because generators are awesome.

So to take it all the way... separating the output into individual files:

```<code>with open(filename, 'r') as fh_in:
    for (i, nested_iter) in enumerate(fresco_iter(fh_in)):
        with open('{}.part-{:04d}'.format(filename, i), 'w') as fh_out:
            for line in nested_iter:
                fh_out.write(line)
</code>```

Will output just the numbers to separate files named fort.16.part-0000 and fort.16.part-0001.

I hope this helps, happy coding!

Body:
I'm trying to write a code to read Fresco files and plot the results. Fresco produces one big file that looks something like this

theta  sigma
1        0.1
2        0.1
3        0.2
...
END
some text...
theta   sigma
1        0.3
2        0.2
...
END
more data...

I want to produce a new file after every 'END' to analyze the data separately. I tried some of the solutions proposed to other answers like

with open('fort.16', 'r') as infile, open('output_fort.16', 'w') as outfile:
copy= False
for line in infile:
    if line.strip() == '# legend':
        copy = True
        continue
    elif line.strip()=='End':
        copy = False
    elif copy:
        outfile.write(line)

but this is not what i need.
Im fairly new to python so any help is much appreciated.

Body:
I managed to solve this with a nested generator:

import re

SECTION_START = re.compile(r'^\s*theta\s+sigma\s*$')
SECTION_END = re.compile(r'^\s*END\s*$')

def fresco_iter(stream):
    def inner(stream):
        # Yields each line until an end marker is found (or EOF)
        for line in stream:
            if line and not SECTION_END.match(line):
                yield line
                continue
            break

    # Find a start marker, then break off into a nested iterator
    for line in stream:
        if line:
            if SECTION_START.match(line):
                yield inner(stream)
            continue
        break

The fresco_iter method returns a generator that can be for-looped over. It returns 1 generator per section of theta sigma pairs.

>>> with open('fort.16', 'r') as fh:
...     print(list(fresco_iter(fh)))
[<generator object fresco_iter.<locals>.inner at 0x7fbc6da15678>,
 <generator object fresco_iter.<locals>.inner at 0x7fbc6da15570>]

So to make use of this, you create your own nested loop to process the nested generators.

filename = 'fort.16'

with open(filename, 'r') as fh:
    for nested_iter in fresco_iter(fh):
        print('--- start')
        for line in nested_iter:
            print(line.rstrip())
        print('--- end')

would output...

--- start
1        0.1
2        0.1
3        0.2
--- end
--- start
1        0.3
2        0.2
--- end

This strategy only ever holds 1 line of your input file in memory at a time, so would work for any size file, on even the smallest device... because generators are awesome.

So to take it all the way... separating the output into individual files:

with open(filename, 'r') as fh_in:
    for (i, nested_iter) in enumerate(fresco_iter(fh_in)):
        with open('{}.part-{:04d}'.format(filename, i), 'w') as fh_out:
            for line in nested_iter:
                fh_out.write(line)

Will output just the numbers to separate files named fort.16.part-0000 and fort.16.part-0001.

I hope this helps, happy coding!


问:
Magnetic dipole in python
I looked at this code:

```<code>import numpy as np
from matplotlib import pyplot as plt

def dipole(m, r, r0):
    """
    Calculation of field B in point r. B is created by a dipole moment m located in r0.
    """
# R = r - r0 - subtraction of elements of vectors r and r0, transposition of array
    R = np.subtract(np.transpose(r), r0).T
# Spatial components of r are the outermost axis
    norm_R = np.sqrt(np.einsum("i...,i...", R, R)) # einsum - Einsteinova sumace
# Dot product of R and m
    m_dot_R = np.tensordot(m, R, axes=1)
# Computation of B
    B = 3 * m_dot_R * R / norm_R**5 - np.tensordot(m, 1 / norm_R**3, axes=0)
    B *= 1e-7   # abbreviation for B = B * 1e-7, multiplication B of 1e-7, permeability of vacuum: 4\pi * 10^(-7)
# The result is the magnetic field B
    return B

X = np.linspace(-1, 1)
Y = np.linspace(-1, 1)

Bx, By = dipole(m=[0, 1], r=np.meshgrid(X, Y), r0=[-0.2,0.8])

plt.figure(figsize=(8, 8))
plt.streamplot(X, Y, Bx, By)
plt.margins(0, 0)

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

It shows the following figure:

Is it possible to get coordinates of one line of force? I don't understand how it is plotted.

答:
The streamplot returns a container object 'StreamplotSet' with two parts:

lines: a LineCollection of the streamlines

arrows: a PatchCollection containing FancyArrowPatch objects (these are the triangular arrows)

c.lines.get_paths() gives all the segments. Iterating through these segments, their vertices can be examined. When a segment starts where the previous ended, both belong to the same curve. Note that each segment is a short straight line; many segments are used together to form a streamline curve.

The code below demonstrates iterating through the segments. To show what's happening, each segment is converted to an array of 2D points suitable for plt.plot. Default, plt.plot colors each curve with a new color (repeating every 10). The dots show where each of the short straight segments are located.

To find one particular curve, you could hover with the mouse over the starting point, and note the x coordinate of that point. And then test for that coordinate in the code. As an example, the curve that starts near x=0.48 is drawn in a special way.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import patches

def dipole(m, r, r0):
    R = np.subtract(np.transpose(r), r0).T
    norm_R = np.sqrt(np.einsum("i...,i...", R, R))
    m_dot_R = np.tensordot(m, R, axes=1)
    B = 3 * m_dot_R * R / norm_R**5 - np.tensordot(m, 1 / norm_R**3, axes=0)
    B *= 1e-7
    return B

X = np.linspace(-1, 1)
Y = np.linspace(-1, 1)

Bx, By = dipole(m=[0, 1], r=np.meshgrid(X, Y), r0=[-0.2,0.8])

plt.figure(figsize=(8, 8))
c = plt.streamplot(X, Y, Bx, By)
c.lines.set_visible(False)
paths = c.lines.get_paths()
prev_end = None
start_indices = []
for index, segment in enumerate(paths):
    if not np.array_equal(prev_end, segment.vertices[0]):  # new segment
        start_indices.append(index)
    prev_end = segment.vertices[-1]
for i0, i1 in zip(start_indices, start_indices[1:] + [len(paths)]):
    # get all the points of the curve that starts at index i0
    curve = np.array([paths[i].vertices[0] for i in range(i0, i1)] + [paths[i1 - 1].vertices[-1]])
special_x_coord = 0.48
for i0, i1 in zip(start_indices, start_indices[1:] + [len(paths)]):
    # get all the points of the curve that starts at index i0
    curve = np.array([paths[i].vertices[0] for i in range(i0, i1)] + [paths[i1 - 1].vertices[-1]])
    if abs(curve[0,0] - special_x_coord) < 0.01:  # draw one curve in a special way
        plt.plot(curve[:, 0], curve[:, 1], '-', lw=10, alpha=0.3)
    else:
        plt.plot(curve[:, 0], curve[:, 1], '.', ls='-')

plt.margins(0, 0)
plt.show()
```

Title: Magnetic dipole in python

Body:
I looked at this code:

import numpy as np
from matplotlib import pyplot as plt

def dipole(m, r, r0):
    """
    Calculation of field B in point r. B is created by a dipole moment m located in r0.
    """
# R = r - r0 - subtraction of elements of vectors r and r0, transposition of array
    R = np.subtract(np.transpose(r), r0).T
# Spatial components of r are the outermost axis
    norm_R = np.sqrt(np.einsum("i...,i...", R, R)) # einsum - Einsteinova sumace
# Dot product of R and m
    m_dot_R = np.tensordot(m, R, axes=1)
# Computation of B
    B = 3 * m_dot_R * R / norm_R**5 - np.tensordot(m, 1 / norm_R**3, axes=0)
    B *= 1e-7   # abbreviation for B = B * 1e-7, multiplication B of 1e-7, permeability of vacuum: 4\pi * 10^(-7)
# The result is the magnetic field B
    return B

X = np.linspace(-1, 1)
Y = np.linspace(-1, 1)

Bx, By = dipole(m=[0, 1], r=np.meshgrid(X, Y), r0=[-0.2,0.8])

plt.figure(figsize=(8, 8))
plt.streamplot(X, Y, Bx, By)
plt.margins(0, 0)

plt.show()

It shows the following figure:

Is it possible to get coordinates of one line of force? I don't understand how it is plotted.