问:
SQL Server Stored Proc - What is returned to a variable if no data?
If, using the following code in a MS SQL Server 2008 stored procedure:

```<code>    DECLARE @PROD_ID VARCHAR(20)

    SELECT @PROD_ID = MYTABLE.PROD
    FROM MYTABLE
    WHERE MYTABLE.DEVID = @DEVCODE
</code>```

DEVCODE does not exist, what will PROD_ID contain? I've tried printing it, but it prints what seems to be a space. However, testing it for space fails. Also, testing for NULL fails. OR, should I be testing for empty in a different manner?

Thanks for reading
BBz

答:
If the @DEVCODE id doesn't exist then @PROD_ID will remain null.

You can't use COALESCE or ISNULL inside the SELECT @PROD_ID = ... statement because it won't return any records at all.

However, you can do:

```<code>DECLARE @PROD_ID VARCHAR(20)

SELECT @PROD_ID = MYTABLE.PROD
FROM MYTABLE
WHERE MYTABLE.DEVID = @DEVCODE

IF (@PROD_ID is null) BEGIN
  -- do something
END
</code>```

Body:
If, using the following code in a MS SQL Server 2008 stored procedure:

    DECLARE @PROD_ID VARCHAR(20)

    SELECT @PROD_ID = MYTABLE.PROD
    FROM MYTABLE
    WHERE MYTABLE.DEVID = @DEVCODE

DEVCODE does not exist, what will PROD_ID contain? I've tried printing it, but it prints what seems to be a space. However, testing it for space fails. Also, testing for NULL fails. OR, should I be testing for empty in a different manner?

Thanks for reading
BBz

Body:
If the @DEVCODE id doesn't exist then @PROD_ID will remain null.

You can't use COALESCE or ISNULL inside the SELECT @PROD_ID = ... statement because it won't return any records at all.

However, you can do:

DECLARE @PROD_ID VARCHAR(20)

SELECT @PROD_ID = MYTABLE.PROD
FROM MYTABLE
WHERE MYTABLE.DEVID = @DEVCODE

IF (@PROD_ID is null) BEGIN
  -- do something
END


来源: stackexchange

问:
What happens when an Azure Logic App is disabled?
What happens when an Azure Logic App is disabled?

Does the current "run" finish, or is it terminated at whatever action is currently on?

In our case, we have a logic app that has a trigger on a message being added to a Service Bus queue ... the Logic App is doing a Peek/Lock read of the message

Various actions, including a SQL Db write, and finishing with a Service Bus complete on the message

If the current run finishes, then we don't have to worry, as that particular message has been "processed"

But if the current run is terminated wherever it is, Service Bus will return the message to the queue after the timeout, and then when the Logic App is re-enabled, we'd re-process the original message from the Service Bus queue

答: Current in flight runs will finish, but the trigger will stop checking for new events and invoking new runs. You can cancel runs to stop ones that are in progress, but currently is a separate gesture to just disable. </p>

ContentLicense: CC BY-SA 3.0


问:
Watson AlchemyLanguage - How do I set the parameters for a CombinedCall
Unfortunately I can't properly tag this question since tags for AlchemyLanguage don't already exist.
I'm trying to retrieve multiple extracts from Watson using a combined call.
Issuing calls for individual data extracts works as expected, but when I attempt to setup params for a combined call only null is returned for each extract.
According to the examples utilizing JSON it seems that 'extract':'sentiment' is the required pairing.

None of these calls work:

```<code>params.put(AlchemyLanguage.EXTRACT, AlchemyLanguage.SENTIMENT);
params.put(AlchemyLanguage.EXTRACT, AlchemyEndPoints.AlchemyAPI.SENTIMENT);
params.put(AlchemyLanguage.EXTRACT, DocumentSentiment.class);
params.put(AlchemyLanguage.TARGET, AlchemyEndPoints.AlchemyAPI.SENTIMENT);
params.put(AlchemyLanguage.TARGET, DocumentSentiment.class);
params.put(AlchemyLanguage.TARGET, AlchemyLanguage.SENTIMENT);

CombinedResults results=service.getCombinedResults(params).execute();
System.out.println(results.getSentiment());
</code>```

null

答:
You need to use the extract parameter as key and list the functions you want to use.

```<code>AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("API_KEY")
Map<String, Object> params = new HashMap<String, Object>();

params.put(AlchemyLanguage.EXTRACT, "authors,concepts,dates,doc-emotion,entities,feeds,keywords,pub-date,relations,typed-rels,doc-sentiment,taxonomy,title");

CombinedResults results=service.getCombinedResults(params).execute();
System.out.println(results);
</code>```

For more information on how to configure each of the functions listed in the extract parameter see the API Reference.

Body:
Unfortunately I can't properly tag this question since tags for AlchemyLanguage don't already exist.
I'm trying to retrieve multiple extracts from Watson using a combined call.
Issuing calls for individual data extracts works as expected, but when I attempt to setup params for a combined call only null is returned for each extract.
According to the examples utilizing JSON it seems that 'extract':'sentiment' is the required pairing.

None of these calls work:

params.put(AlchemyLanguage.EXTRACT, AlchemyLanguage.SENTIMENT);
params.put(AlchemyLanguage.EXTRACT, AlchemyEndPoints.AlchemyAPI.SENTIMENT);
params.put(AlchemyLanguage.EXTRACT, DocumentSentiment.class);
params.put(AlchemyLanguage.TARGET, AlchemyEndPoints.AlchemyAPI.SENTIMENT);
params.put(AlchemyLanguage.TARGET, DocumentSentiment.class);
params.put(AlchemyLanguage.TARGET, AlchemyLanguage.SENTIMENT);

CombinedResults results=service.getCombinedResults(params).execute();
System.out.println(results.getSentiment());

null

Body:
You need to use the extract parameter as key and list the functions you want to use.

AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("API_KEY")
Map<String, Object> params = new HashMap<String, Object>();

params.put(AlchemyLanguage.EXTRACT, "authors,concepts,dates,doc-emotion,entities,feeds,keywords,pub-date,relations,typed-rels,doc-sentiment,taxonomy,title");

CombinedResults results=service.getCombinedResults(params).execute();
System.out.println(results);

For more information on how to configure each of the functions listed in the extract parameter see the API Reference.


问:
C++ Calling Member Function by Function Pointer Error
I'm programming a Discrete Event Simulator (DES) where events will be user programmed functions.
I have a Class called UserEvents and a private member function called Add

```<code>    void Add(const void *Parameters, void *ReturnValue);
</code>```

I'm trying to make a vector that would store the following struct:

```<code> typedef struct FunctionPointerAlias { std::string FAlias; void(UserEvents::*FPointer)(const void*, void*); };
</code>```

Based on a string, I want to call different functions. Thus switch would be nice but switch can't handle strings (and I don't want to hash my strings).
So I made a vector with a struct (string Alias, FunctionPointer) and then I'll iterate over my vector looking for the user's inputed string, recovering the corresponding function pointer and calling it.

All user functions should be of type void, receiving parameters and returning values through void* pointers as such:

```<code>void UserEvents::Add(const void *Parameters, void *ReturnValue)
{
    int *A = (int*)Parameters;
    int *B = A;
    B++;

    int *C = (int*)ReturnValue;
    *C = *A + *B;

    //memcpy(ReturnValue, &C, sizeof(int));
    return;
}
</code>```

(TL;DR) The problem lies when I try to call the function pointed by the function pointer. I get the error "Expression preceding parentheses of apparent call must have (pointer-to-) function type" on the line right above return in the "Add" if.

```<code>    void UserEvents::Choose(const std::string Alias, const void *Parameters, void *ReturnValue)
{
    if (Alias == "Example")
    {
        // *ReturnValue = Function(Parameters)
        return;
    }

    if (Alias == "Add") {
        void (UserEvents::*FunctionPointer)(const void*, void*) = &UserEvents::Add;
        (*FunctionPointer)(Parameters, ReturnValue);
        return;
    }
}
</code>```

答:
I think the syntax to invoke that member function by pointer should be e.g.

```<code>( this->*FunctionPointer )( Parameters, ReturnValue );
</code>```

C++ has two operators, .* and ->*, specifically created to access class members by pointer. Here's an article on the topic. The ubiquitous * operator just doesn't work with class member pointers.

Body:
I'm programming a Discrete Event Simulator (DES) where events will be user programmed functions.
I have a Class called UserEvents and a private member function called Add

    void Add(const void *Parameters, void *ReturnValue);

I'm trying to make a vector that would store the following struct:

 typedef struct FunctionPointerAlias { std::string FAlias; void(UserEvents::*FPointer)(const void*, void*); };

Based on a string, I want to call different functions. Thus switch would be nice but switch can't handle strings (and I don't want to hash my strings).
So I made a vector with a struct (string Alias, FunctionPointer) and then I'll iterate over my vector looking for the user's inputed string, recovering the corresponding function pointer and calling it.

All user functions should be of type void, receiving parameters and returning values through void* pointers as such:

void UserEvents::Add(const void *Parameters, void *ReturnValue)
{
    int *A = (int*)Parameters;
    int *B = A;
    B++;

    int *C = (int*)ReturnValue;
    *C = *A + *B;

    //memcpy(ReturnValue, &C, sizeof(int));
    return;
}

(TL;DR) The problem lies when I try to call the function pointed by the function pointer. I get the error "Expression preceding parentheses of apparent call must have (pointer-to-) function type" on the line right above return in the "Add" if.

    void UserEvents::Choose(const std::string Alias, const void *Parameters, void *ReturnValue)
{
    if (Alias == "Example")
    {
        // *ReturnValue = Function(Parameters)
        return;
    }

    if (Alias == "Add") {
        void (UserEvents::*FunctionPointer)(const void*, void*) = &UserEvents::Add;
        (*FunctionPointer)(Parameters, ReturnValue);
        return;
    }
}

Body:
I think the syntax to invoke that member function by pointer should be e.g.

( this->*FunctionPointer )( Parameters, ReturnValue );

C++ has two operators, .* and ->*, specifically created to access class members by pointer. Here's an article on the topic. The ubiquitous * operator just doesn't work with class member pointers.


问:
Entity Framework Core Calibre
I am writing an EF core wrapper for the Calibre database. I have configured the BookTagLink table as follows

```<code>builder.HasKey(x => new {x.TagId, x.BookId });

builder.Property(b => b.BookId)
            .ForSqliteHasColumnName("book")
            .IsRequired();

builder.Property(b => b.TagId)
            .ForSqliteHasColumnName("tag")
            .IsRequired();
</code>```

However var book = tag.BookTagLinks.Select(b => b.Book); errors out with:

Value cannot be null.\r\nParameter name: source

I think the problem is that there is an Id (bigint) set up as the primary key on the BookTagLinks table and when I use the book and tag ids it does not connect the dots and can't find the source.

How do one sets up a many to many relationship when there is a simple key instead of a foreign key in the database?

答:
Turns out I brainfarted. I declared BookTagLinks as an ICollection but forgot to instantiate it in the constructor.
Additionally I found out that you have to specify the relationships.
I modified my class as follow
`public override void Map(EntityTypeBuilder builder)
        {
            builder.ToTable("books_tags_link");

```<code>        base.Map(builder);

        builder.HasKey(x => new {x.TagId, x.BookId });

        builder.HasOne(bt => bt.Book)
            .WithMany(b => b.BookTagLinks)
            .HasForeignKey(bt => bt.BookId);

        builder.HasOne(bt => bt.Tag)
            .WithMany(t => t.BookTagLinks)
            .HasForeignKey(bt => bt.TagId);

        builder.Property(b => b.BookId)
            .ForSqliteHasColumnName("book")
            .IsRequired();

        builder.Property(b => b.TagId)
            .ForSqliteHasColumnName("tag")
            .IsRequired();

    }`
</code>```

And now everything works...

Title: Entity Framework Core Calibre

Body:
I am writing an EF core wrapper for the Calibre database. I have configured the BookTagLink table as follows

builder.HasKey(x => new {x.TagId, x.BookId });

builder.Property(b => b.BookId)
            .ForSqliteHasColumnName("book")
            .IsRequired();

builder.Property(b => b.TagId)
            .ForSqliteHasColumnName("tag")
            .IsRequired();

However var book = tag.BookTagLinks.Select(b => b.Book); errors out with:

Value cannot be null.\r\nParameter name: source

I think the problem is that there is an Id (bigint) set up as the primary key on the BookTagLinks table and when I use the book and tag ids it does not connect the dots and can't find the source.

How do one sets up a many to many relationship when there is a simple key instead of a foreign key in the database?

Body:
Turns out I brainfarted. I declared BookTagLinks as an ICollection but forgot to instantiate it in the constructor.
Additionally I found out that you have to specify the relationships.
I modified my class as follow
`public override void Map(EntityTypeBuilder builder)
        {
            builder.ToTable("books_tags_link");

        base.Map(builder);

        builder.HasKey(x => new {x.TagId, x.BookId });

        builder.HasOne(bt => bt.Book)
            .WithMany(b => b.BookTagLinks)
            .HasForeignKey(bt => bt.BookId);

        builder.HasOne(bt => bt.Tag)
            .WithMany(t => t.BookTagLinks)
            .HasForeignKey(bt => bt.TagId);

        builder.Property(b => b.BookId)
            .ForSqliteHasColumnName("book")
            .IsRequired();

        builder.Property(b => b.TagId)
            .ForSqliteHasColumnName("tag")
            .IsRequired();

    }`

And now everything works...


问:
Func vs. Action vs. Predicate
With real examples and their use, can someone please help me understand:

When do we need a Func<T, ..> delegate?

When do we need an Action<T> delegate?

When do we need a Predicate<T> delegate?

答:
The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

```<code> list.Select(x => x.SomeProperty)
</code>```

or filtering:

```<code> list.Where(x => x.SomeValue == someOtherValue)
</code>```

or key selection:

```<code> list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
</code>```

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

ContentLicense: CC BY-SA 4.0

Title: Func vs. Action vs. Predicate

Body:
The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.


问:
Change Color on Colors on Pie Chart Based on Cell Value
Hi just getting started with VBA excel - is there a way to color segments of a pie chart based on a value that does not directly feed into the Pie Chart?
My sample data would look like this :

```<code>        Steps   % Complete    Status
        Step1         100%          B  (Blue)
        Step2         50%           R  (Red)
        Step3         30%           G  (Green)
        Step4         15%           A  (Yellow)
</code>```

The Pie Chart will be generated only using the first two columns (Steps and % Complete). But I want each of the segments for the pie chart to be colored based on the Status column.

答:
First set in conditional formatting with vba to color each of the chart input cells (% Complete Column) according to the color represented by the Status Column (if Status "R" then %Complete color Red) - sample below

** Note - regular conditional formatting will not work

```<code>Dim status_value As Range
Set status_value = Sheets("Sheet 1").Cells(20, 3) -
    If mycell.Value = "B" Then
        mycell2.Interior.color = RGB(0, 112, 192) 'Blue
    ElseIf mycell.Value = "R" Then
        mycell2.Interior.color = RGB(255, 0, 0) ' Red
    ElseIf mycell.Value = "A" Then
        mycell2.Interior.color = RGB(255, 192, 0) 'Amber
    ElseIf mycell.Value = "G" Then
        mycell2.Interior.color = RGB(0, 176, 80) ' Green
    ElseIf mycell.Value = "NA" Then
        mycell2.Interior.color = RGB(166, 166, 166) 'Grey
    End If
</code>```

The below code will color the chart according to the interior color of the cells providing the values for the chart

```<code>Sub ColorCharts()
        For Each ch In ActiveSheet.ChartObjects
            For Each ser In ch.Chart.SeriesCollection
            s = Split(ser.Formula, ",")
                For i = 1 To UBound(ser.Values)
                    ser.Points(i).Interior.color = Range(s(2)).Cells(i).Interior.color
                Next i
            Next ser
        Next ch
        End Sub
</code>```

Body:
Hi just getting started with VBA excel - is there a way to color segments of a pie chart based on a value that does not directly feed into the Pie Chart?
My sample data would look like this :

        Steps   % Complete    Status
        Step1         100%          B  (Blue)
        Step2         50%           R  (Red)
        Step3         30%           G  (Green)
        Step4         15%           A  (Yellow)

The Pie Chart will be generated only using the first two columns (Steps and % Complete). But I want each of the segments for the pie chart to be colored based on the Status column.

Body:
First set in conditional formatting with vba to color each of the chart input cells (% Complete Column) according to the color represented by the Status Column (if Status "R" then %Complete color Red) - sample below

** Note - regular conditional formatting will not work

Dim status_value As Range
Set status_value = Sheets("Sheet 1").Cells(20, 3) -
    If mycell.Value = "B" Then
        mycell2.Interior.color = RGB(0, 112, 192) 'Blue
    ElseIf mycell.Value = "R" Then
        mycell2.Interior.color = RGB(255, 0, 0) ' Red
    ElseIf mycell.Value = "A" Then
        mycell2.Interior.color = RGB(255, 192, 0) 'Amber
    ElseIf mycell.Value = "G" Then
        mycell2.Interior.color = RGB(0, 176, 80) ' Green
    ElseIf mycell.Value = "NA" Then
        mycell2.Interior.color = RGB(166, 166, 166) 'Grey
    End If

The below code will color the chart according to the interior color of the cells providing the values for the chart

Sub ColorCharts()
        For Each ch In ActiveSheet.ChartObjects
            For Each ser In ch.Chart.SeriesCollection
            s = Split(ser.Formula, ",")
                For i = 1 To UBound(ser.Values)
                    ser.Points(i).Interior.color = Range(s(2)).Cells(i).Interior.color
                Next i
            Next ser
        Next ch
        End Sub


问:
Export all http requests on a specific page to txt/csv
I use SIEGE to test my web server performance. For a more realistic test the best way to go would be to  have SIEGE hit the web page (website.com/our-company) and all static assets (.css, .js, .png, .jpg). Everything that you see on the firefox / chrome debbuing tools, except of course from resources loaded from external servers (cdn.facebook, apis.google.com).

I am running several tests so it is a pain to manually collect all asset urls. Is there a tool that I can use to load a web page and export the url for everything that was loaded?

This is firefox debugging. If I could export this to txt or csv, it would be perfect.

I tried CURL on debian CLI but I am no experct. Any tool will help, it does't have to be a plugin of Firefox / Chrome.

Best regards.

答:
As you guys know, the HAR file format is a JSON file. So... I looked for a JSON to CSV converter and found this:

https://json-csv.com/

This worked for my HAR file that I got from GTmetrix.com. Enjoy!


问:
EditText: Differentiate between text change by setText() or by keyboard input
I have an EditText View which is edited by setText() from my code and by the user via (soft/hard) keyboard and - if possible by speech input. I want to handle input made by my code in another way than normal user input: if a user input happens, a internal event shall be fired. But I don't know how to differentiate between both. Previously - when developing on the emulator - I used the onKeyDown() method to catch user input. However, when testing on a real device, I found out, that onKeyDown() isn't triggered from soft keyboard input. Additionally speech input wouldn't be recognized by this, though I consider this to be a minor flaw. So that solution is no option for me.

On the other hand there is the onTextChanged() method, but this is triggered by both setText() and keyboard input. So how can I differentiate between both or which method is only called by user input, but not when using setText(), so can I overwrite it?

答:
I was having this issue when rotating the device. My editText is inside a dialog. Here's how I solved it:</p>

```<code>editText.addTextChangedListener(
    new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            String newValue = s.toString();

           String oldValue = (String) editText.getTag();

            if (newValue.length() > 0) {
                editText.setTag(newValue);
            }

            boolean itReallyChanged = oldValue != null && !newValue.equals(oldValue) && !newValue.isEmpty();
            if (itReallyChanged) {
                // Pretty sure the user genuinely changed this value,
                // not the device rotation
            }
        }
    }
);
</code>```

Body:
I was having this issue when rotating the device. My editText is inside a dialog. Here's how I solved it:

editText.addTextChangedListener(
    new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            String newValue = s.toString();

           String oldValue = (String) editText.getTag();

            if (newValue.length() > 0) {
                editText.setTag(newValue);
            }

            boolean itReallyChanged = oldValue != null && !newValue.equals(oldValue) && !newValue.isEmpty();
            if (itReallyChanged) {
                // Pretty sure the user genuinely changed this value,
                // not the device rotation
            }
        }
    }
);


问:
Incorrect file recieved when user replies with attachment
My bot prompts the user for an attachment in a dialog and is suppose to receive an image from the user and save the content name, url and type of that file to variables. However, the file I am receiving is not the file the user sent. Instead its retrieving a file named 'blob' (no extension) from this link:

https://webchat.botframework.com/attachments/GkLhiqJcvH019mP0iGBKvo/0000052/0/blob?t=X5ICiUrhFas.dAA.RwBrAEwAaABpAHEASgBjAHYASAAwADEAOQBtAFAAMABpAEcAQgBLAHYAbwAtADAAMAAwADAAMAA1ADIA.mcEiHxuH0gE.VMcp6Yduqgc.4xT1ZTOvCX-B7A0nLto6eZNFrFi-0xSzGk5AKmA-EPE

That file contains:

```<code>{"type":"message","from":{"id":"9n0I1ZqSrLF","name":"You"},"locale":"en-US","timestamp":"2017-02-14T21:12:32.074Z","channelData":{"clientActivityId":"1487106689866.9060198022610071.8"}}
</code>```

Here is the code for the attachment prompt. This prompt is within a dialog:

```<code>private async Task getAttach(IDialogContext context, IAwaitable<IEnumerable<Attachment>> result)
    {
        IEnumerable<Attachment> list = await result;
        Attachment attachment = list.FirstOrDefault();

        string filename = attachment.Name;
        string url = attachment.ContentUrl;
        string contentType = attachment.ContentType;

        //Set attachmentFileNames
        if (attachmentFileNames == null)
        {
            attachmentFileNames = "";
        }

        attachmentFileNames += contentType;
        attachmentFileNames += ",";
        numberOfFiles++;

        //Set attachmentFileURLs
        if (attachmentFileURLs == null)
        {
            attachmentFileURLs = "";
        }

        attachmentFileURLs += url;
        attachmentFileURLs += ",";

        attachmentHasBeenAdded = true;
        await FirstMessageReceivedAsync(context, result);

    }
</code>```

Here is how I am handling attachments in the  message controller. This is within the Post Task:

```<code>ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity.Attachments != null && activity.Attachments.Any())
            {
                hasaAttachment = true;
                var attachment = activity.Attachments.First();
                using (HttpClient httpClient = new HttpClient())
                {
                    // Skype & MS Teams attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
                    if ((activity.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase) || activity.ChannelId.Equals("msteams", StringComparison.InvariantCultureIgnoreCase))
                        && new Uri(attachment.ContentUrl).Host.EndsWith("skype.com"))
                    {
                        var token = await new MicrosoftAppCredentials().GetTokenAsync();
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    }

                    var responseMessage = await httpClient.GetAsync(attachment.ContentUrl);

                    var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;

                    Activity reply = activity.CreateReply($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received. URL: {attachment.ContentUrl}");

                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }
</code>```

I am following this example:
Receive Attachment Bot Sample

In the emulator it works correctly but the published version on azure does not. The code is very similar to the example so I don't see why the bot is not detecting the user's files.
How do I receive the correct file (the file the user replied with)?

答:
The attachments will be in elements 1 onwards. E.g.

```<code>Attachment attachment = list.ElementAt(1);
</code>```

The webchat (and maybe other platforms) has a weird quirk where it adds a blob file at the start of IEnumerable 'result' when prompting and getting attachments from the user.

```<code>private async Task getAttach(IDialogContext context, IAwaitable<IEnumerable<Attachment>> result)
{...}
</code>```

Body:
My bot prompts the user for an attachment in a dialog and is suppose to receive an image from the user and save the content name, url and type of that file to variables. However, the file I am receiving is not the file the user sent. Instead its retrieving a file named 'blob' (no extension) from this link:

https://webchat.botframework.com/attachments/GkLhiqJcvH019mP0iGBKvo/0000052/0/blob?t=X5ICiUrhFas.dAA.RwBrAEwAaABpAHEASgBjAHYASAAwADEAOQBtAFAAMABpAEcAQgBLAHYAbwAtADAAMAAwADAAMAA1ADIA.mcEiHxuH0gE.VMcp6Yduqgc.4xT1ZTOvCX-B7A0nLto6eZNFrFi-0xSzGk5AKmA-EPE

That file contains:

{"type":"message","from":{"id":"9n0I1ZqSrLF","name":"You"},"locale":"en-US","timestamp":"2017-02-14T21:12:32.074Z","channelData":{"clientActivityId":"1487106689866.9060198022610071.8"}}

Here is the code for the attachment prompt. This prompt is within a dialog:

private async Task getAttach(IDialogContext context, IAwaitable<IEnumerable<Attachment>> result)
    {
        IEnumerable<Attachment> list = await result;
        Attachment attachment = list.FirstOrDefault();

        string filename = attachment.Name;
        string url = attachment.ContentUrl;
        string contentType = attachment.ContentType;

        //Set attachmentFileNames
        if (attachmentFileNames == null)
        {
            attachmentFileNames = "";
        }

        attachmentFileNames += contentType;
        attachmentFileNames += ",";
        numberOfFiles++;

        //Set attachmentFileURLs
        if (attachmentFileURLs == null)
        {
            attachmentFileURLs = "";
        }

        attachmentFileURLs += url;
        attachmentFileURLs += ",";

        attachmentHasBeenAdded = true;
        await FirstMessageReceivedAsync(context, result);

    }

Here is how I am handling attachments in the  message controller. This is within the Post Task:

ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity.Attachments != null && activity.Attachments.Any())
            {
                hasaAttachment = true;
                var attachment = activity.Attachments.First();
                using (HttpClient httpClient = new HttpClient())
                {
                    // Skype & MS Teams attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
                    if ((activity.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase) || activity.ChannelId.Equals("msteams", StringComparison.InvariantCultureIgnoreCase))
                        && new Uri(attachment.ContentUrl).Host.EndsWith("skype.com"))
                    {
                        var token = await new MicrosoftAppCredentials().GetTokenAsync();
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    }

                    var responseMessage = await httpClient.GetAsync(attachment.ContentUrl);

                    var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;

                    Activity reply = activity.CreateReply($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received. URL: {attachment.ContentUrl}");

                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }

I am following this example:
Receive Attachment Bot Sample

In the emulator it works correctly but the published version on azure does not. The code is very similar to the example so I don't see why the bot is not detecting the user's files.
How do I receive the correct file (the file the user replied with)?

Body:
The attachments will be in elements 1 onwards. E.g.

Attachment attachment = list.ElementAt(1);

The webchat (and maybe other platforms) has a weird quirk where it adds a blob file at the start of IEnumerable 'result' when prompting and getting attachments from the user.

private async Task getAttach(IDialogContext context, IAwaitable<IEnumerable<Attachment>> result)
{...}


问:
Centering SVG inside an SVG
I am working on a project where we need to let users upload their SVG and give them an ability to perform certain modifications on them.

For that, we have defined a root level SVG and group within which user uploaded SVG will be rendered.

The problem I am facing is that different SVG with different ViewBox settings get rendered at different location in the root SVG. I have attached sample images of this and a fiddle to play with it: https://jsfiddle.net/gsp4k6n7/2/

Here is the code that loads up the SVG in the root:

```<code>loadImage = function(svgData) {
   var root = document.getElementById('__root_group__');
   root.innerHTML = svgData;
}
</code>```

I have tried transform: translate(x, y) but that does not seem to work in every case. For example, the following code was able to center the first image with DigitalOcean logo, but the second image was way off center.

```<code>alignImage = function() {
  var svg = document.getElementById('__root_svg__');
  var group = document.getElementById('__root_group__');

  var sr = svg.getBoundingClientRect();
  var gr = group.getBoundingClientRect();

  var x = (sr.width - gr.width) / 2;
  var y = (sr.height - gr.height) / 2;

  group.setAttribute('transform', `translate(${x},${y})`);
}
</code>```

What is the best way to center align all of the imported SVG both horizontally and vertically in the root SVG?

答:
Your alignImage() function would have worked like this:

```<code>alignImage = function() {
  var svg = document.getElementById('__root_svg__');
  // reference the inserted SVG element
  var innerSvg = svg.getElementById('__root_group__').firstElementChild;

  var sr = svg.getBoundingClientRect();
  //extract the vieBox values - note the more robust RegEx
  var vb = innerSvg.getAttribute('viewBox').split(/[,\s]+/);

  // do not overwrite existing width/height values
  var width = innerSvg.hasAttribute('width') ? innerSvg.getAttribute('width') : vb[2];
  var height = innerSvg.hasAttribute('height') ? innerSvg.getAttribute('height') : vb[3];

  var x = (sr.width - width) / 2;
  var y = (sr.height - height) / 2;

  innerSvg.setAttribute('x', x);
  innerSvg.setAttribute('y', y);
  innerSvg.setAttribute('width', width);
  innerSvg.setAttribute('height', height);
}
</code>```

Although, this does not provide for cases when the inner SVG is larger than the outer.

Title: Centering SVG inside an SVG

Body:
I am working on a project where we need to let users upload their SVG and give them an ability to perform certain modifications on them.

For that, we have defined a root level SVG and group within which user uploaded SVG will be rendered.

The problem I am facing is that different SVG with different ViewBox settings get rendered at different location in the root SVG. I have attached sample images of this and a fiddle to play with it: https://jsfiddle.net/gsp4k6n7/2/

Here is the code that loads up the SVG in the root:

loadImage = function(svgData) {
   var root = document.getElementById('__root_group__');
   root.innerHTML = svgData;
}

I have tried transform: translate(x, y) but that does not seem to work in every case. For example, the following code was able to center the first image with DigitalOcean logo, but the second image was way off center.

alignImage = function() {
  var svg = document.getElementById('__root_svg__');
  var group = document.getElementById('__root_group__');

  var sr = svg.getBoundingClientRect();
  var gr = group.getBoundingClientRect();

  var x = (sr.width - gr.width) / 2;
  var y = (sr.height - gr.height) / 2;

  group.setAttribute('transform', `translate(${x},${y})`);
}

What is the best way to center align all of the imported SVG both horizontally and vertically in the root SVG?

Body:
Your alignImage() function would have worked like this:

alignImage = function() {
  var svg = document.getElementById('__root_svg__');
  // reference the inserted SVG element
  var innerSvg = svg.getElementById('__root_group__').firstElementChild;

  var sr = svg.getBoundingClientRect();
  //extract the vieBox values - note the more robust RegEx
  var vb = innerSvg.getAttribute('viewBox').split(/[,\s]+/);

  // do not overwrite existing width/height values
  var width = innerSvg.hasAttribute('width') ? innerSvg.getAttribute('width') : vb[2];
  var height = innerSvg.hasAttribute('height') ? innerSvg.getAttribute('height') : vb[3];

  var x = (sr.width - width) / 2;
  var y = (sr.height - height) / 2;

  innerSvg.setAttribute('x', x);
  innerSvg.setAttribute('y', y);
  innerSvg.setAttribute('width', width);
  innerSvg.setAttribute('height', height);
}

Although, this does not provide for cases when the inner SVG is larger than the outer.


问:
StringBuilder vs String concatenation in toString() in Java
Given the 2 toString() implementations below, which one is preferred:

```<code>public String toString(){
    return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
</code>```

or

```<code>public String toString(){
    StringBuilder sb = new StringBuilder(100);
    return sb.append("{a:").append(a)
          .append(", b:").append(b)
          .append(", c:").append(c)
          .append("}")
          .toString();
}
</code>```

?

More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from + concat to  StringBuilder?

答:
In Java 9 the version 1 should be faster because it is converted to invokedynamic call. More details can be found in JEP-280:

The idea is to replace the entire StringBuilder append dance with a simple invokedynamic call to java.lang.invoke.StringConcatFactory, that will accept the values in the need of concatenation.

Body:
Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}

or

public String toString(){
    StringBuilder sb = new StringBuilder(100);
    return sb.append("{a:").append(a)
          .append(", b:").append(b)
          .append(", c:").append(c)
          .append("}")
          .toString();
}

?

More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from + concat to  StringBuilder?


问:
How to Use Jaxb for nested POJO class to generate XML model in Java
I'm using JAXB to create an xml data model and it seems to be working really well for non-complex XML model but as soon as I get into a slightly complex XML, JAXB doesn't seem to work as well.

This is the XML-generation I would like to acheive:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SampleRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="Sample.xsd">

    <Name>Sample Name</Name>
    <Description>This is a description</Description>
    <Graph>Graph test</Graph>

    <VerifyAttr>
        <Data>id</Data>
        <Value>32</Value>
    </VerifyAttr>

    <VeirfyXpath>
        <MemXpath>/Root/Name</MemXpath>
        <Value>Mosawi</Value>
    </<VeirfyXpath>>

</SampleRoot>
</code>```

This is the Nested Pojo class I created (should I not create a nested pojo? Perhaps separate them out?):

```<code>package com.sample.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="SampleRoot")
public class Sample {
    private String name;
    private String description;
    private String graph;

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    @XmlElement
    public void setDescription(String description) {
        this.description = description;
    }
    public String getGraph() {
        return graph;
    }
    @XmlElement
    public void setGraph(String graph) {
        this.graph = graph;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class VerifyAttr {
        private String data;
        private String value;

        public String getData() {
            return data;
        }
        @XmlElement
        public void setData(String data) {
            this.data = data;
        }
        public String getValue() {
            return value;
        }
        @XmlElement
        public void setValue(String value) {
            this.value = value;
        }

    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class VerifyXpath {
        private String memXpath;
        private String value;

        public String getMemXpath() {
            return memXpath;
        }
        @XmlElement
        public void setMemXpath(String memXpath) {
            this.memXpath = memXpath;
        }
        public String getValue() {
            return value;
        }
        @XmlElement
        public void setValue(String value) {
            this.value = value;
        }

    }

}
</code>```

And here is the demo to exercise the pojo model:

```<code>public static void main(String[] args) {
    Sample sample = new Sample();

    sample.setName("Name");
    sample.setDescription("This is a description");
    sample.setGraph("Graph Test");

    VerifyAttr va = sample.new VerifyAttr();
    va.setData("id");
    va.setValue("32");

    VerifyXpath vx = sample.new VerifyXpath();
    vx.setMemXpath("/Root/Name");
    vx.setValue("Mosawi");

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(sample, new File("Sample.xml") );
        jaxbMarshaller.marshal(sample, System.out);

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

The problem I have is that the full XML as defined above is not generated. This is what is generated:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SampleRoot>
    <description>This is a description</description>
    <graph>Graph Test</graph>
    <name>Name</name>
</SampleRoot>
</code>```

What am I doing wrong? Why am I not getting the model XML as I should above? The problem is with demo main?

答:
Okay so I was able to figure this out by reading some JaxB documentation. I've decoupled the POJOs into 3 classes and adjusted the Jaxb annotations:

Sample.java
VerifyAttr.java
VerifyXpath.java

VerifyAttr.java

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(propOrder={"dataAttr","valueAttr"})
public class VerifyAttr {
    //...
}
</code>```

VerifyXpath.java

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(propOrder={"dataXpath","valueXpath"})
public class VerifyAttr {
    //...
}
</code>```

and a top level for root node:

Sample.java

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class VerifyAttr {
    @XmlElement(name="VerifyAttr", type=VerifyAttr.class)
    private ArrayList<VerifyAttr> va;

    @XmlElement(name="VerifyXpath", type=VerifyXpath.class)
    private ArrayList<VerifyXpath> vx;

    // some other fields
    //..getter and setters
}
</code>```

Hopefully this helps someone else new to Jaxb

Body:
I'm using JAXB to create an xml data model and it seems to be working really well for non-complex XML model but as soon as I get into a slightly complex XML, JAXB doesn't seem to work as well.

This is the XML-generation I would like to acheive:

<?xml version="1.0" encoding="UTF-8"?>
<SampleRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="Sample.xsd">

    <Name>Sample Name</Name>
    <Description>This is a description</Description>
    <Graph>Graph test</Graph>

    <VerifyAttr>
        <Data>id</Data>
        <Value>32</Value>
    </VerifyAttr>

    <VeirfyXpath>
        <MemXpath>/Root/Name</MemXpath>
        <Value>Mosawi</Value>
    </<VeirfyXpath>>

</SampleRoot>

This is the Nested Pojo class I created (should I not create a nested pojo? Perhaps separate them out?):

package com.sample.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="SampleRoot")
public class Sample {
    private String name;
    private String description;
    private String graph;

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    @XmlElement
    public void setDescription(String description) {
        this.description = description;
    }
    public String getGraph() {
        return graph;
    }
    @XmlElement
    public void setGraph(String graph) {
        this.graph = graph;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class VerifyAttr {
        private String data;
        private String value;

        public String getData() {
            return data;
        }
        @XmlElement
        public void setData(String data) {
            this.data = data;
        }
        public String getValue() {
            return value;
        }
        @XmlElement
        public void setValue(String value) {
            this.value = value;
        }

    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class VerifyXpath {
        private String memXpath;
        private String value;

        public String getMemXpath() {
            return memXpath;
        }
        @XmlElement
        public void setMemXpath(String memXpath) {
            this.memXpath = memXpath;
        }
        public String getValue() {
            return value;
        }
        @XmlElement
        public void setValue(String value) {
            this.value = value;
        }

    }

}

And here is the demo to exercise the pojo model:

public static void main(String[] args) {
    Sample sample = new Sample();

    sample.setName("Name");
    sample.setDescription("This is a description");
    sample.setGraph("Graph Test");

    VerifyAttr va = sample.new VerifyAttr();
    va.setData("id");
    va.setValue("32");

    VerifyXpath vx = sample.new VerifyXpath();
    vx.setMemXpath("/Root/Name");
    vx.setValue("Mosawi");

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(sample, new File("Sample.xml") );
        jaxbMarshaller.marshal(sample, System.out);

    } catch(Exception e) {
        e.printStackTrace();
    }
}

The problem I have is that the full XML as defined above is not generated. This is what is generated:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SampleRoot>
    <description>This is a description</description>
    <graph>Graph Test</graph>
    <name>Name</name>
</SampleRoot>

What am I doing wrong? Why am I not getting the model XML as I should above? The problem is with demo main?

Body:
Okay so I was able to figure this out by reading some JaxB documentation. I've decoupled the POJOs into 3 classes and adjusted the Jaxb annotations:

Sample.java
VerifyAttr.java
VerifyXpath.java

VerifyAttr.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(propOrder={"dataAttr","valueAttr"})
public class VerifyAttr {
    //...
}

VerifyXpath.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(propOrder={"dataXpath","valueXpath"})
public class VerifyAttr {
    //...
}

and a top level for root node:

Sample.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class VerifyAttr {
    @XmlElement(name="VerifyAttr", type=VerifyAttr.class)
    private ArrayList<VerifyAttr> va;

    @XmlElement(name="VerifyXpath", type=VerifyXpath.class)
    private ArrayList<VerifyXpath> vx;

    // some other fields
    //..getter and setters
}

Hopefully this helps someone else new to Jaxb


问:
How to store the XML response that we got from using an api in javascript?
I am trying to use an api , and I send a request asking for some data using the javascript . The server replies back with an xml data , which I don't know where to store or how to access the XML . I can parse it using JSON , but need to know how to store the XML data first .  </p>

答:
If that API you're using requires some sort of authentication, don't use Javascript for that. It's client-side code and all authentication shows up in it.

Matt Ball is right; you cannot "parse it using JSON". You can however have a PHP script perform that task for you with its xml_parser_* functions.

ContentLicense: CC BY-SA 2.5


问:
How to replace optional group with regex and Golang
I am trying to translate this:

```<code>{% img <right> /images/testing %}
</code>```

into this:

```<code>{{< figure <class="right"> src="/images/testing" >}}
</code>```

with regex in Golang. The part in <> in the source string is optional.

I have this code, which seems to work in the main test case, when the first capturing group exists ("right"):

```<code>regexp.MustCompile(`{%\s*img\s*(\p{L}*)\s+([/\S]+)\s+%}`)
.ReplaceAllString("{% img right /images/testing %}", "{{< figure class=\"$1\" src=\"$2\" >}}")
</code>```

If the optional group is missing, however, I get:

```<code>{{< figure class="" src="/images/testing" >}}
</code>```

which is not what I need - I want the entire class="" section gone, like this:

```<code>{{< figure src="/images/testing" >}}
</code>```

Is this possible? Can I indicate somehow in the replacing string:

```<code>{{< figure class=\"$1\" src=\"$2\" >}}
</code>```

that I want the additional text ("class=") gone if the optional group is empty?

答:
Go regexp do not support conditional statements and the Replace family of regexp functions doesn't either.
The solution to this depends on the number of special cases you have.

If you only have the one case I'd suggest to just do a two pass replacement: First replace all occurences with the attribute set, then replace all the cases without the attribute (on play):

```<code>txt := `{% img right /images/testing %}\n{% img /images/testing %}`

// without attribute
txt = regexp.MustCompile(`{%\s*img\s*([/\S]+)\s+%}`).
  ReplaceAllString(txt, "{{< figure src=\"$1\" >}}")

// with attribute
txt = regexp.MustCompile(`{%\s*img\s*(\p{L}*)\s+([/\S]+)\s+%}`).
  ReplaceAllString(txt, "{{< figure class=\"$1\" src=\"$2\" >}}")
</code>```

If you say this is inefficient I say: probably, yes. If you want something more efficient (i.e. something that does not iterate the source string twice) then you have to build something more akin to a parser which decides at the time of detection which format to use. A rough sketch of this would be something like this (on play):

```<code>src := []byte("ok" + "{% img right /images/testing %}" + "this" +
              "{% img /images/testing %}" + "no?")
dst := bytes.NewBufferString("")
cidx := 0

for _, match := range p.FindAllSubmatchIndex(src, -1) {
    dst.Write(src[cidx:match[0]])
    dst.WriteString(newFormat(src, src[match[2]:match[3]], src[match[4]:match[5]]))
    cidx = match[1]
}
dst.Write(src[cidx:])
</code>```

In this example you copy everything from your source text src to a buffer dst, replacing every occurrence of your pattern with the output of the value of a function. This function can then decide to include specific formatting or not.

Body:
I am trying to translate this:

{% img <right> /images/testing %}

into this:

{{< figure <class="right"> src="/images/testing" >}}

with regex in Golang. The part in <> in the source string is optional.

I have this code, which seems to work in the main test case, when the first capturing group exists ("right"):

regexp.MustCompile(`{%\s*img\s*(\p{L}*)\s+([/\S]+)\s+%}`)
.ReplaceAllString("{% img right /images/testing %}", "{{
}}")

If the optional group is missing, however, I get:

{{
}}

which is not what I need - I want the entire class="" section gone, like this:

{{
}}

Is this possible? Can I indicate somehow in the replacing string:

{{
}}

that I want the additional text ("class=") gone if the optional group is empty?

Body:
Go regexp do not support conditional statements and the Replace family of regexp functions doesn't either.
The solution to this depends on the number of special cases you have.

If you only have the one case I'd suggest to just do a two pass replacement: First replace all occurences with the attribute set, then replace all the cases without the attribute (on play):

txt := `{% img right /images/testing %}\n{% img /images/testing %}`

// without attribute
txt = regexp.MustCompile(`{%\s*img\s*([/\S]+)\s+%}`).
  ReplaceAllString(txt, "{{< figure src=\"$1\" >}}")

// with attribute
txt = regexp.MustCompile(`{%\s*img\s*(\p{L}*)\s+([/\S]+)\s+%}`).
  ReplaceAllString(txt, "{{< figure class=\"$1\" src=\"$2\" >}}")

If you say this is inefficient I say: probably, yes. If you want something more efficient (i.e. something that does not iterate the source string twice) then you have to build something more akin to a parser which decides at the time of detection which format to use. A rough sketch of this would be something like this (on play):

src := []byte("ok" + "{% img right /images/testing %}" + "this" +
              "{% img /images/testing %}" + "no?")
dst := bytes.NewBufferString("")
cidx := 0

for _, match := range p.FindAllSubmatchIndex(src, -1) {
    dst.Write(src[cidx:match[0]])
    dst.WriteString(newFormat(src, src[match[2]:match[3]], src[match[4]:match[5]]))
    cidx = match[1]
}
dst.Write(src[cidx:])

In this example you copy everything from your source text src to a buffer dst, replacing every occurrence of your pattern with the output of the value of a function. This function can then decide to include specific formatting or not.


问:
jQuery/Javascript: variable NOT updating after GET call
I'm trying to read from a text file and put the information inside it into an Array. However, it seems I am doing something wrong.

```<code>var Level = function(ctx) {
    this.ctx = ctx;
    this.lvlWidth = 0;
    this.lvlHeight = 0;

    this.map = [];

    this.loadLevel = function(){
    var start = 0;
    var end = 0;
    this.lvlHeight = 25;
    this.lvlWidth = 21;

    $.get("1.txt", function(data){
        start = data.indexOf("0");
        end = data.lastIndexOf("#");
        this.map = data.slice(start, end - 2).split(" ");
    }, "text");

    console.log(this.map);
   };
}; // end Level
</code>```

On console, it says that my variable this.map is an EMPTY ARRAY. It doesn't modify itself, and I don't know why. I checked other answers and people said that this problem happens if you don't declare your variable (in my case map) outside the function, but you can clearly see that I did. Ironically enough, this.lvlWidth and this.lvlHeight DO change to 21 and 25 respectively. Can anyone tell me why does map doesn't update?

Here is the info of 1.txt (which is on the same folder as this file):

```<code># startleveldata
0 0 0 0 0 0 0 0 0 113 21 113 0 0 0 0 0 0 0 0 0
0 107 100 100 100 100 100 100 100 106 0 105 100 100 100 100 100 100 100 108 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 101 3 120 2 113 2 111 100 108 2 107 100 112 2 113 2 120 3 101 0
0 101 2 2 2 101 2 2 2 101 2 101 2 2 2 101 2 2 2 101 0
0 101 2 111 100 106 2 113 2 110 2 110 2 113 2 105 100 112 2 101 0
0 101 2 2 2 2 2 101 2 2 2 2 2 101 2 2 2 2 2 101 0
0 101 2 120 2 111 100 130 100 112 2 111 100 130 100 112 2 120 2 101 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 105 100 108 2 113 2 111 100 100 100 100 100 112 2 113 2 107 100 106 0
0 0 0 101 2 101 2 2 0 0 10 0 0 2 2 101 2 101 0 0 0
111 100 100 106 2 105 112 2 107 112 1 111 108 2 111 106 2 105 100 100 112
20 0 0 0 2 0 0 2 101 11 12 13 101 2 0 0 2 0 0 0 20
111 133 100 112 2 111 112 2 105 100 100 100 106 2 111 112 2 111 100 133 112
0 101 2 2 2 0 0 2 0 0 0 0 0 2 0 0 2 2 2 101 0
0 101 2 120 2 107 112 2 111 100 100 100 112 2 111 108 2 120 2 101 0
0 101 2 2 2 101 2 2 0 0 4 0 0 2 2 101 2 2 2 101 0
0 105 133 112 2 110 2 111 100 100 133 100 100 112 2 110 2 111 133 106 0
0 0 101 2 2 2 2 2 2 2 101 2 2 2 2 2 2 2 101 0 0
0 0 101 2 111 112 2 111 108 2 101 2 107 112 2 111 112 2 101 0 0
107 100 106 2 2 2 2 2 101 2 101 2 101 2 2 2 2 2 105 100 108
101 2 2 2 111 100 112 2 110 2 110 2 110 2 111 100 112 2 2 2 101
101 3 120 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 120 3 101
101 2 2 2 107 100 100 100 100 108 0 107 100 100 100 100 108 2 2 2 101
105 100 100 100 106 0 0 0 0 110 21 110 0 0 0 0 105 100 100 100 106
# endleveldata
</code>```

EDIT: I made it work guys! Problem is I needed to call a callback function that would call this function again. Following user @ACOMIT001 advice, I used the .then() function after my $.get(). I extracted the $get function, put it on my main program, and on the .then() function I called loadLevel(), and it works. I can't really explain why but this works for me now. Thanks everyone for your help/

答:
$.get is an asynchronous method. It returns straight away after being called rather waiting for a response from your server. Hence why this.map will be empty.

Try something like this:

```<code>var that = this;

$.get("1.txt", function(data){
    start = data.indexOf("0");
    end = data.lastIndexOf("#");
    that.map = data.slice(start, end - 2).split(" ");
}, "text").then(function () {
    console.log(that.map);
});
</code>```

Also as the previous answer states, the scope of this is changing.

Body:
I'm trying to read from a text file and put the information inside it into an Array. However, it seems I am doing something wrong.

var Level = function(ctx) {
    this.ctx = ctx;
    this.lvlWidth = 0;
    this.lvlHeight = 0;

    this.map = [];

    this.loadLevel = function(){
    var start = 0;
    var end = 0;
    this.lvlHeight = 25;
    this.lvlWidth = 21;

    $.get("1.txt", function(data){
        start = data.indexOf("0");
        end = data.lastIndexOf("#");
        this.map = data.slice(start, end - 2).split(" ");
    }, "text");

    console.log(this.map);
   };
}; // end Level

On console, it says that my variable this.map is an EMPTY ARRAY. It doesn't modify itself, and I don't know why. I checked other answers and people said that this problem happens if you don't declare your variable (in my case map) outside the function, but you can clearly see that I did. Ironically enough, this.lvlWidth and this.lvlHeight DO change to 21 and 25 respectively. Can anyone tell me why does map doesn't update?

Here is the info of 1.txt (which is on the same folder as this file):

# startleveldata
0 0 0 0 0 0 0 0 0 113 21 113 0 0 0 0 0 0 0 0 0
0 107 100 100 100 100 100 100 100 106 0 105 100 100 100 100 100 100 100 108 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 101 3 120 2 113 2 111 100 108 2 107 100 112 2 113 2 120 3 101 0
0 101 2 2 2 101 2 2 2 101 2 101 2 2 2 101 2 2 2 101 0
0 101 2 111 100 106 2 113 2 110 2 110 2 113 2 105 100 112 2 101 0
0 101 2 2 2 2 2 101 2 2 2 2 2 101 2 2 2 2 2 101 0
0 101 2 120 2 111 100 130 100 112 2 111 100 130 100 112 2 120 2 101 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 105 100 108 2 113 2 111 100 100 100 100 100 112 2 113 2 107 100 106 0
0 0 0 101 2 101 2 2 0 0 10 0 0 2 2 101 2 101 0 0 0
111 100 100 106 2 105 112 2 107 112 1 111 108 2 111 106 2 105 100 100 112
20 0 0 0 2 0 0 2 101 11 12 13 101 2 0 0 2 0 0 0 20
111 133 100 112 2 111 112 2 105 100 100 100 106 2 111 112 2 111 100 133 112
0 101 2 2 2 0 0 2 0 0 0 0 0 2 0 0 2 2 2 101 0
0 101 2 120 2 107 112 2 111 100 100 100 112 2 111 108 2 120 2 101 0
0 101 2 2 2 101 2 2 0 0 4 0 0 2 2 101 2 2 2 101 0
0 105 133 112 2 110 2 111 100 100 133 100 100 112 2 110 2 111 133 106 0
0 0 101 2 2 2 2 2 2 2 101 2 2 2 2 2 2 2 101 0 0
0 0 101 2 111 112 2 111 108 2 101 2 107 112 2 111 112 2 101 0 0
107 100 106 2 2 2 2 2 101 2 101 2 101 2 2 2 2 2 105 100 108
101 2 2 2 111 100 112 2 110 2 110 2 110 2 111 100 112 2 2 2 101
101 3 120 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 120 3 101
101 2 2 2 107 100 100 100 100 108 0 107 100 100 100 100 108 2 2 2 101
105 100 100 100 106 0 0 0 0 110 21 110 0 0 0 0 105 100 100 100 106
# endleveldata

EDIT: I made it work guys! Problem is I needed to call a callback function that would call this function again. Following user @ACOMIT001 advice, I used the .then() function after my $.get(). I extracted the $get function, put it on my main program, and on the .then() function I called loadLevel(), and it works. I can't really explain why but this works for me now. Thanks everyone for your help/

Body:
$.get is an asynchronous method. It returns straight away after being called rather waiting for a response from your server. Hence why this.map will be empty.

Try something like this:

var that = this;

$.get("1.txt", function(data){
    start = data.indexOf("0");
    end = data.lastIndexOf("#");
    that.map = data.slice(start, end - 2).split(" ");
}, "text").then(function () {
    console.log(that.map);
});

Also as the previous answer states, the scope of this is changing.


问:
MySQL Querying Duplicates
So, I have a database called teams, and it currently looks like this:

```<code>team_id | leader_id | student_id
1       | 123456    | 1234
2       | 1234      | 123456, 1234567890
3       | 1234      | 123456
4       | 0         | 12345, 1234, 1234567890
5       | 0         |
6       | 0         |
</code>```

My students database looks like this

```<code>student_id | first_name | last_name
123456     | qwer       | qwer
0          | asd        | zxc
1234567890 | mmm        |nnn
</code>```

The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.

Example:

If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.

Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id

My PHP

```<code><?php

    error_reporting(0);

    require '../../connect.php';

    $leader_id = $_POST['leader_id'];
    $student_id = array(
        $_POST['student_id_1'],
        $_POST['student_id_2'],
        $_POST['student_id_3'],
        $_POST['student_id_4'],
        $_POST['student_id_5'],
        $_POST['student_id_6']
    );

    $students_save = array();

    if(!empty($leader_id)) {

        foreach ($student_id as $id) {

            if(!empty($id)) {

                array_push($students_save, $id);

            }
        }

        foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");

                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }

    } else if(empty($leader_id)){

        header("Location: ../../../admin.php?Please add you're input values");

    }

 ?>
</code>```

答:
As you edited your question,

all you need is to break out of your foreach loop, if you $result is
  successfull so add break in if($result) rest of the code will remain
  the same

See the code below

```<code>    <?php

foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");
                        break; // add break here, as if your condition
                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }
</code>```

Title: MySQL Querying Duplicates

Body:
So, I have a database called teams, and it currently looks like this:

team_id | leader_id | student_id
1       | 123456    | 1234
2       | 1234      | 123456, 1234567890
3       | 1234      | 123456
4       | 0         | 12345, 1234, 1234567890
5       | 0         |
6       | 0         |

My students database looks like this

student_id | first_name | last_name
123456     | qwer       | qwer
0          | asd        | zxc
1234567890 | mmm        |nnn

The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.

Example:

If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.

Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id

My PHP

<?php

    error_reporting(0);

    require '../../connect.php';

    $leader_id = $_POST['leader_id'];
    $student_id = array(
        $_POST['student_id_1'],
        $_POST['student_id_2'],
        $_POST['student_id_3'],
        $_POST['student_id_4'],
        $_POST['student_id_5'],
        $_POST['student_id_6']
    );

    $students_save = array();

    if(!empty($leader_id)) {

        foreach ($student_id as $id) {

            if(!empty($id)) {

                array_push($students_save, $id);

            }
        }

        foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");

                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }

    } else if(empty($leader_id)){

        header("Location: ../../../admin.php?Please add you're input values");

    }

 ?>

Body:
As you edited your question,

all you need is to break out of your foreach loop, if you $result is
  successfull so add break in if($result) rest of the code will remain
  the same

See the code below

    <?php

foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");
                        break; // add break here, as if your condition
                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }


问:
How do I find the 10 largest subarrays efficiently?
I need to find 10 largest subarrays (maximum length) in an array with the condition arr[high] - arr[low] < delta. It's taking 50 seconds right now (using Python). I'm able to find the maximum sub-array by modifying the algorithm to find maximum subarray with sum < somevalue. Right now, I'm just using a for loop and deleting the maximum sub-array found after every iteration. I tried a lot of things but am back to this now as nothing worked correctly. The array is sorted.

```<code>with open(in_file) as f_in, open(out_file, 'w') as f_out:
    dct = {}
    mainlst = []
    # Read a file and store values in mainlst and map to some strings using dct

    for i in range(10):
        start = 0
        end = 0
        maxim = 0
        diff = 0
        current = 1
        max_start = 0
        max_end = 0
        while end < len(mainlst)-1:
            end += 1
            diff = mainlst[end] - mainlst[start]
            current += 1
            while diff > delta:
                start += 1
                diff = mainlst[end] - mainlst[start]
                current -= 1
            if maxim < current:
                maxim = current
                max_start = start
                max_end = end

        print("".join([dct[mainlst[max_start]], ",", str(maxim)]), file=f_out)

        del mainlst[max_start:max_end+1]
</code>```

Edit: I forgot to mention another condition. The sub-arrays cannot overlap.

答:
There is a O(N lg N) algorithm:

Iterate through each element, from small to large, set current element to A[low], O(N)

Binary search the index of A[high] which fulfill the inequality, O(lg N)

Push the length and the pair of (low, high) in a priority queue or any data structure which maintained order in O(lg N) times

Pop the top 10, or top N items and that's the answer

EDITED

Thanks to @m69, using two pointers a better O(N) can be achieved:

Iterate through each element, from small to large, set two pointers low and high pointing to the first element initially

Move the high pointer to the right until A[high] - A[low] >= delta, push the length and the pair of (low, high) in a priority queue or any data structure which maintained order in O(lg N) times.

For your special case, you can simply use an array of size 10 to store the longest 10 subarray, then you can use O(1) to maintain this array.

Move low pointer to right , repeat step 2.

Note that low is always smaller than or equal to high, and both pointers always move to right only, each iterate through the list once. So it is O(N), or it is O(N lg N) for general case using priority queue.

Body:
I need to find 10 largest subarrays (maximum length) in an array with the condition arr[high] - arr[low] < delta. It's taking 50 seconds right now (using Python). I'm able to find the maximum sub-array by modifying the algorithm to find maximum subarray with sum < somevalue. Right now, I'm just using a for loop and deleting the maximum sub-array found after every iteration. I tried a lot of things but am back to this now as nothing worked correctly. The array is sorted.

with open(in_file) as f_in, open(out_file, 'w') as f_out:
    dct = {}
    mainlst = []
    # Read a file and store values in mainlst and map to some strings using dct

    for i in range(10):
        start = 0
        end = 0
        maxim = 0
        diff = 0
        current = 1
        max_start = 0
        max_end = 0
        while end < len(mainlst)-1:
            end += 1
            diff = mainlst[end] - mainlst[start]
            current += 1
            while diff > delta:
                start += 1
                diff = mainlst[end] - mainlst[start]
                current -= 1
            if maxim < current:
                maxim = current
                max_start = start
                max_end = end

        print("".join([dct[mainlst[max_start]], ",", str(maxim)]), file=f_out)

        del mainlst[max_start:max_end+1]

Edit: I forgot to mention another condition. The sub-arrays cannot overlap.


问:
Convert a tree to a matrix Python 3
I'm trying to convert a Tree: (list Nat (listof Tree)) to a graph matrix but I do not know where to start. I'm not looking for code but more so ideas on how to approach this problem.

For example, a tree is

```<code>aTree = [3 , [
             [1 , []] ,
             [0 , [
                  [2 , []] ,
                  [5 , []]
                  ]
             ] ,
             [4 , []]
            ]
         ]
</code>```

Which would look like:

```<code>       3
    /  |  \
   1   0   4
      / \
     2   5
</code>```

And the matrix would be

```<code>aM =

    [[0 , 0 , 1 , 1 , 0 , 1] ,
     [0 , 0 , 0 , 1 , 0 , 0] ,
     [1 , 0 , 0 , 0 , 0 , 0] ,
     [1 , 1 , 0 , 0 , 1 , 0] ,
     [0 , 0 , 0 , 1 , 0 , 0] ,
     [1 , 0 , 0 , 0 , 0 , 0]]
</code>```

the function would be treetomatrix(Tree, N) where N is the number of vertices in the tree. So treetomatrix(aTree, 6) => aM.

Any suggestions would be much appreciated.

答:
The really hard part of this question is how to change the weird list structure you're using into a dictionary.  (If you don't know about dictionaries, read up on them.  They do what you're trying to make your list do, but much more naturally.) I've skipped that for the moment, and will do that next.

```<code>aTree = {3 : {
               1: {},
               0:{  2: {},
                    5: {}
                 }
               4:{}
             }
        }

def tree_to_matrix(tree, n):
    return tree_to_mat(tree, [[0 for i in range(n)] for j in range(n)])

def tree_to_mat(tree, mat):
    for k, v in tree.items():
        for i in v.keys():
            mat[i][k] = mat[k][i] = 1
        mat = tree_to_mat(v, mat)
    return mat

print(tree_to_matrix(aTree, 6))
</code>```

prints

```<code>[[0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0]]
</code>```

Which is our desired output.  You may find it easier to read your input into a custom Tree class and then write a method for that class to generate the matrices.  The trick is to use recursion and realize that you have to set both mat[i][k] and mat[k][i] at the same time.

EDIT: Here's my hacky way of turning your list into a dict.

```<code>def dictify(l):
    return {l[0]: d_helper(l[1])}

def d_helper(l):
    d={}
    for i in l:
        d.update(dictify(i))
    return d

dictify(aTree)
</code>```

There's a better way, but this works.

Title: Convert a tree to a matrix Python 3

Body:
I'm trying to convert a Tree: (list Nat (listof Tree)) to a graph matrix but I do not know where to start. I'm not looking for code but more so ideas on how to approach this problem.

For example, a tree is

aTree = [3 , [
             [1 , []] ,
             [0 , [
                  [2 , []] ,
                  [5 , []]
                  ]
             ] ,
             [4 , []]
            ]
         ]

Which would look like:

       3
    /  |  \
   1   0   4
      / \
     2   5

And the matrix would be

aM =

    [[0 , 0 , 1 , 1 , 0 , 1] ,
     [0 , 0 , 0 , 1 , 0 , 0] ,
     [1 , 0 , 0 , 0 , 0 , 0] ,
     [1 , 1 , 0 , 0 , 1 , 0] ,
     [0 , 0 , 0 , 1 , 0 , 0] ,
     [1 , 0 , 0 , 0 , 0 , 0]]

the function would be treetomatrix(Tree, N) where N is the number of vertices in the tree. So treetomatrix(aTree, 6) => aM.

Any suggestions would be much appreciated.

Body:
The really hard part of this question is how to change the weird list structure you're using into a dictionary.  (If you don't know about dictionaries, read up on them.  They do what you're trying to make your list do, but much more naturally.) I've skipped that for the moment, and will do that next.

aTree = {3 : {
               1: {},
               0:{  2: {},
                    5: {}
                 }
               4:{}
             }
        }

def tree_to_matrix(tree, n):
    return tree_to_mat(tree, [[0 for i in range(n)] for j in range(n)])

def tree_to_mat(tree, mat):
    for k, v in tree.items():
        for i in v.keys():
            mat[i][k] = mat[k][i] = 1
        mat = tree_to_mat(v, mat)
    return mat

print(tree_to_matrix(aTree, 6))

prints

[[0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0]]

Which is our desired output.  You may find it easier to read your input into a custom Tree class and then write a method for that class to generate the matrices.  The trick is to use recursion and realize that you have to set both mat[i][k] and mat[k][i] at the same time.

EDIT: Here's my hacky way of turning your list into a dict.

def dictify(l):
    return {l[0]: d_helper(l[1])}

def d_helper(l):
    d={}
    for i in l:
        d.update(dictify(i))
    return d

dictify(aTree)

There's a better way, but this works.


问:
How can I format a floating point number in Scala inside a StringBuilder?
Good evening SO,

I want to format a floating point number in Scala within my StringBuilder. The code below works but is verbose. Surely there's a more concise way to do the same thing.

Thank you.

```<code>var myDouble: Double = 1.23456789
val stringBuilder = StringBuilder.newBuilder
stringBuilder.append(s"My double: ${BigDecimal(myDouble).setScale(5, BigDecimal.RoundingMode.HALF_UP)}")
println(stringBuilder.toString())
</code>```

答:
Something like this?</p>

```<code>new StringBuilder(f"$myDouble%.5f")
res0: StringBuilder = 1.23457
</code>```

Body:
Good evening SO,

I want to format a floating point number in Scala within my StringBuilder. The code below works but is verbose. Surely there's a more concise way to do the same thing.

Thank you.

var myDouble: Double = 1.23456789
val stringBuilder = StringBuilder.newBuilder
stringBuilder.append(s"My double: ${BigDecimal(myDouble).setScale(5, BigDecimal.RoundingMode.HALF_UP)}")
println(stringBuilder.toString())

Body:
Something like this?

new StringBuilder(f"$myDouble%.5f")
res0: StringBuilder = 1.23457


问:
Remove "Social Title" from order form in Prestashop?
I have just downloaded and installed the latest version of Prestashop. And found out there is a Social Title-option in order checkout form.

I want to remove that. I have found how to remove the Mr and Mrs boxes. But the whole row and label "Social Title" remains.

Have tried to search on Google for an answer but can't find. Some answers refer to the addresses.tpl. But I think the templates might been changed since these threads.

In fact, I have tried to search for "social" in the whole template directory and can't find anything related to this.

The nearest I get is in the ../templates/customer/_partials/customer-form.tpl. And I think it's rendered where this is:

```<code><section>
    {block "form_fields"}
      {foreach from=$formFields item="field"}
        {block "form_field"}
          {form_field field=$field}
        {/block}
      {/foreach}
    {/block}
  </section>
</code>```

So, maybe the social title isn't able to change from templates anymore?

So, where do I change it nowadays?

答:
Shop Parameters -> Customer Settings -> Titles - Delete titles
themes/xxx/templates/_partials/form-fields.tpl 9th line change

```<code>  {if $field.type !== 'checkbox'}
    {$field.label}
  {/if}
</code>```

to

```<code>  {if $field.type !== 'checkbox' and $field.type !== 'radio-buttons'}
    {$field.label}
  {/if}
</code>```

Yeah, it's kind of dummy workaround, but it works.

UPDATE:
More proper way would be to comment the block:

```<code>        $genderField = (new FormField)
        ->setName('id_gender')
        ->setType('radio-buttons')
        ->setLabel(
            $this->translator->trans(
                'Social title', [], 'Shop.Forms.Labels'
            )
        )
    ;
    foreach (Gender::getGenders($this->language->id) as $gender) {
        $genderField->addAvailableValue($gender->id, $gender->name);
    }
    $format[$genderField->getName()] = $genderField;
</code>```

You can find it in /classes/form/CustomerFormatter.php

Body:
I have just downloaded and installed the latest version of Prestashop. And found out there is a Social Title-option in order checkout form.

I want to remove that. I have found how to remove the Mr and Mrs boxes. But the whole row and label "Social Title" remains.

Have tried to search on Google for an answer but can't find. Some answers refer to the addresses.tpl. But I think the templates might been changed since these threads.

In fact, I have tried to search for "social" in the whole template directory and can't find anything related to this.

The nearest I get is in the ../templates/customer/_partials/customer-form.tpl. And I think it's rendered where this is:

    {block "form_fields"}
      {foreach from=$formFields item="field"}
        {block "form_field"}
          {form_field field=$field}
        {/block}
      {/foreach}
    {/block}

So, maybe the social title isn't able to change from templates anymore?

So, where do I change it nowadays?

Body:
Shop Parameters -> Customer Settings -> Titles - Delete titles
themes/xxx/templates/_partials/form-fields.tpl 9th line change

  {if $field.type !== 'checkbox'}
    {$field.label}
  {/if}

to

  {if $field.type !== 'checkbox' and $field.type !== 'radio-buttons'}
    {$field.label}
  {/if}

Yeah, it's kind of dummy workaround, but it works.

UPDATE:
More proper way would be to comment the block:

        $genderField = (new FormField)
        ->setName('id_gender')
        ->setType('radio-buttons')
        ->setLabel(
            $this->translator->trans(
                'Social title', [], 'Shop.Forms.Labels'
            )
        )
    ;
    foreach (Gender::getGenders($this->language->id) as $gender) {
        $genderField->addAvailableValue($gender->id, $gender->name);
    }
    $format[$genderField->getName()] = $genderField;

You can find it in /classes/form/CustomerFormatter.php


问:
How to classify image using IBM Visual Recognition API Version 3
I have written below code in Node.js to create a classifier and then classify an image using Visual Recognition API Version 3, but the image isn't classified with the created classifier.

Same code has worked with earlier version. Please share your thoughts.

Thanks in advance!

```<code>var visual_recognition, params;
var ONE_HOUR = 3600000;
var CLASSIFIERID = [];

    // Create the service wrapper
  visual_recognition = watson.visual_recognition({
     version: 'v3',
     api_key: process.env.API_KEY || '<api-key>',
     version_date: '2015-05-19'
    });
</code>```

Creating classfier:

```<code>params = {
    name: constants.DRIVERNAME,
    driverOne_positive_examples: fs.createReadStream('./public/positive.zip'),
    negative_examples: fs.createReadStream('./public/negative.zip')
    };

    visual_recognition.createClassifier(params, function(err, classifier) {
     if (err){

        res.render('showError',{title:constants.TITLE1,
                                    err:'Something went wrong!'
                                    });
     }

     else{

        CLASSIFIERID.push(classifier.classifier_id);
         }

    });
</code>```

Classify image:

```<code>var parm = {
      images_file: img_classify,
      classifier_ids: CLASSIFIERID,
      threshold: 0.0
    };

visual_recognition.classify(parm, function(err, results) {
    var driverName,driverScore,driverId,driver;

    if (err){
      console.log('Error at classification!!!');

    }

    else{

        console.log('Image has been classified!!!');
    res.json(results);
}
</code>```

答:
You need to specify classifier_ids using an array.

```<code>var parm = {
      images_file: img_classify,
      classifier_ids: [CLASSIFIERID], // <--- See this
      threshold: 0.0
    };

visual_recognition.classify(parm, function(err, results) {
    var driverName,driverScore,driverId,driver;

    if (err){
      console.log('Error at classification!!!');

    }

    else{

        console.log('Image has been classified!!!');
    res.json(results);
}
</code>```

Visual Recognition Node SDK documentation.

Body:
I have written below code in Node.js to create a classifier and then classify an image using Visual Recognition API Version 3, but the image isn't classified with the created classifier.

Same code has worked with earlier version. Please share your thoughts.

Thanks in advance!

var visual_recognition, params;
var ONE_HOUR = 3600000;
var CLASSIFIERID = [];

    // Create the service wrapper
  visual_recognition = watson.visual_recognition({
     version: 'v3',
     api_key: process.env.API_KEY || '<api-key>',
     version_date: '2015-05-19'
    });

Creating classfier:

params = {
    name: constants.DRIVERNAME,
    driverOne_positive_examples: fs.createReadStream('./public/positive.zip'),
    negative_examples: fs.createReadStream('./public/negative.zip')
    };

    visual_recognition.createClassifier(params, function(err, classifier) {
     if (err){

        res.render('showError',{title:constants.TITLE1,
                                    err:'Something went wrong!'
                                    });
     }

     else{

        CLASSIFIERID.push(classifier.classifier_id);
         }

    });

Classify image:

var parm = {
      images_file: img_classify,
      classifier_ids: CLASSIFIERID,
      threshold: 0.0
    };

visual_recognition.classify(parm, function(err, results) {
    var driverName,driverScore,driverId,driver;

    if (err){
      console.log('Error at classification!!!');

    }

    else{

        console.log('Image has been classified!!!');
    res.json(results);
}

Body:
You need to specify classifier_ids using an array.

var parm = {
      images_file: img_classify,
      classifier_ids: [CLASSIFIERID], // <--- See this
      threshold: 0.0
    };

visual_recognition.classify(parm, function(err, results) {
    var driverName,driverScore,driverId,driver;

    if (err){
      console.log('Error at classification!!!');

    }

    else{

        console.log('Image has been classified!!!');
    res.json(results);
}

Visual Recognition Node SDK documentation.


问:
HTML canvas image is fading out after multiple iterations/reusing
I have a portal which is used for collecting orders from users in hand written format.

In my portal, I am using HTML canvas for getting inputs from user.

Once the user write order and submits it, I will read the drawings from the canvas and saves it into my DB.

```<code>HTML

    <canvas height="750" width="768" id="userNotes"></canvas>

Javascript

    var canvas = document.getElementById('userNotes');
    var notesDataURL = canvas.toDataURL();

    saveImageDataToDataBase (notesDataURL);
</code>```

Next time when the user comes for a new order, I will draw this image back into the canvas, so that he can make modifications on the same and submit it as fresh order.

```<code>Javascript
    var canvas = document.getElementById('userNotes');
    var context = canvas.getContext('2d');

    var img = new Image();
    img.src = imageData;
    context.drawImage(img, 0, 0);
</code>```

Problem that I am facing is that after multiple iterations, the image starts fading out.

One observation is that fading is more at the bottom part of the image and less on the top side.

Consider the below sample images,

After 10 iterations image became like this,

Below is a JS FIddle created using sample code, in this after about 25 iterations fading will be visible(issue is visible only in tablet mentioned below).

https://jsfiddle.net/hz8r993v/

Observation:
An observation which I made is the issue is happening only in a specific tablet model, Samsung SM-P550, which is unfortunately the one my application is build for.

I am not able to reproduce this issue while using this application in my laptop, PC or another sm-p650 tablet.

Currently Only happening in all tablets of model SM-P550. Even I am confused with this observation.

I also tried disabling ImageSmoothingEnabled properties, but not helping.

Any leads/clues are appreciated.

答:
I am probably not experienced enough to tell you what about that tablet version, or what in your HTML/Javascript could be causing this issue. I am, however, good at problem solving, and solving puzzles.

I have two possible guesses:

Is there anything in your code, which could lead to a change in the resolution? The only reason that I think this may be part of the cause, is that because the image is being redrawn on a canvas that  is the same size, any change in the image size could cause the image to become slightly pixilated. and repetitive changes in the image size would only exaggerate this change.

That is probably not the sole cause. I think that there is probably an additional cause because the issue is only present on the one specific tablet version. I am not familiar with that tablet version, but is there anything about its OS or interface that could alter the file when it is saved or redisplayed?

As a side note, it would be nice if you could provide a comparison image, just to see the change.

Hope that this at least points you in the right direction.

Body:
I have a portal which is used for collecting orders from users in hand written format.

In my portal, I am using HTML canvas for getting inputs from user.

Once the user write order and submits it, I will read the drawings from the canvas and saves it into my DB.

HTML

    <canvas height="750" width="768" id="userNotes"></canvas>

Javascript

    var canvas = document.getElementById('userNotes');
    var notesDataURL = canvas.toDataURL();

    saveImageDataToDataBase (notesDataURL);

Next time when the user comes for a new order, I will draw this image back into the canvas, so that he can make modifications on the same and submit it as fresh order.

Javascript
    var canvas = document.getElementById('userNotes');
    var context = canvas.getContext('2d');

    var img = new Image();
    img.src = imageData;
    context.drawImage(img, 0, 0);

Problem that I am facing is that after multiple iterations, the image starts fading out.

One observation is that fading is more at the bottom part of the image and less on the top side.

Consider the below sample images,

After 10 iterations image became like this,

Below is a JS FIddle created using sample code, in this after about 25 iterations fading will be visible(issue is visible only in tablet mentioned below).

https://jsfiddle.net/hz8r993v/

Observation:
An observation which I made is the issue is happening only in a specific tablet model, Samsung SM-P550, which is unfortunately the one my application is build for.

I am not able to reproduce this issue while using this application in my laptop, PC or another sm-p650 tablet.

Currently Only happening in all tablets of model SM-P550. Even I am confused with this observation.

I also tried disabling ImageSmoothingEnabled properties, but not helping.

Any leads/clues are appreciated.


问:
Big Query: How to get top 20 correlations in a table?
I have 100,000 time-series files with a with 2 columns each, date, and value. I will make a table in Google BigQuery and append all time-series to this table so that each append will extend 3 columns, time_series_name, date, value. In the end, I will have 3 columns with millions of rows. What code would I have to use to the top 20 correlated time-series given a time_series_name. I think I would have to do some GROUPBY(time_series_name) and then calculate this time_series_name correlation with every other item, and then sort the items by descending. Is that right? What query code would do this?</p>

答:
Try below,

It assumes you have your table named all_time_series with fields: time_series_name, dt and value and is built per logic you described in your question

#standardSQL
WITH series AS (
  SELECT DISTINCT time_series_name
  FROM all_time_series
),
pairs AS (
  SELECT
    series1.time_series_name AS time_series_1,
    series2.time_series_name AS time_series_2,
    CONCAT(series1.time_series_name, ' - ', series2.time_series_name) AS pair_name
  FROM series AS series1
  JOIN series AS series2
  ON series1.time_series_name < series2.time_series_name
)
SELECT pair_name, CORR(value1, value2) AS correlation
FROM (
  SELECT pair_name, a1.dt AS dt, a1.value AS value1, a2.value AS value2
  FROM pairs AS p
  JOIN all_time_series AS a1
    ON p.time_series_1 = a1.time_series_name
  JOIN all_time_series AS a2
    ON p.time_series_2 = a2.time_series_name
    AND a1.dt = a2.dt
)
GROUP BY pair_name
ORDER BY correlation DESC
LIMIT 20
```

<p>You can test above with dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH all_time_series AS (
  SELECT 'a' AS time_series_name, '2016-01-01' AS dt, 1 AS value UNION ALL
  SELECT 'a', '2016-01-02', 2 UNION ALL
  SELECT 'a', '2016-01-03', 3 UNION ALL

  SELECT 'b', '2016-01-01', 1 UNION ALL
  SELECT 'b', '2016-01-02', 2 UNION ALL
  SELECT 'b', '2016-01-03', 3 UNION ALL

  SELECT 'c', '2016-01-01', 5 UNION ALL
  SELECT 'c', '2016-01-02', 6 UNION ALL
  SELECT 'c', '2016-01-03', 7 UNION ALL

  SELECT 'd', '2016-01-01', 6 UNION ALL
  SELECT 'd', '2016-01-02', 2 UNION ALL
  SELECT 'd', '2016-01-03', 3
),
series AS (
  SELECT DISTINCT time_series_name
  FROM all_time_series
),
pairs AS (
  SELECT
    series1.time_series_name AS time_series_1,
    series2.time_series_name AS time_series_2,
    CONCAT(series1.time_series_name, ' - ', series2.time_series_name) AS pair_name
  FROM series AS series1
  JOIN series AS series2
  ON series1.time_series_name < series2.time_series_name
)
SELECT pair_name, CORR(value1, value2) AS correlation
FROM (
  SELECT pair_name, a1.dt AS dt, a1.value AS value1, a2.value AS value2
  FROM pairs AS p
  JOIN all_time_series AS a1
    ON p.time_series_1 = a1.time_series_name
  JOIN all_time_series AS a2
    ON p.time_series_2 = a2.time_series_name
    AND a1.dt = a2.dt
)
GROUP BY pair_name
ORDER BY correlation DESC
LIMIT 2
</code>```

Body:
Try below,

It assumes you have your table named all_time_series with fields: time_series_name, dt and value and is built per logic you described in your question

#standardSQL
WITH series AS (
  SELECT DISTINCT time_series_name
  FROM all_time_series
),
pairs AS (
  SELECT
    series1.time_series_name AS time_series_1,
    series2.time_series_name AS time_series_2,
    CONCAT(series1.time_series_name, ' - ', series2.time_series_name) AS pair_name
  FROM series AS series1
  JOIN series AS series2
  ON series1.time_series_name < series2.time_series_name
)
SELECT pair_name, CORR(value1, value2) AS correlation
FROM (
  SELECT pair_name, a1.dt AS dt, a1.value AS value1, a2.value AS value2
  FROM pairs AS p
  JOIN all_time_series AS a1
    ON p.time_series_1 = a1.time_series_name
  JOIN all_time_series AS a2
    ON p.time_series_2 = a2.time_series_name
    AND a1.dt = a2.dt
)
GROUP BY pair_name
ORDER BY correlation DESC
LIMIT 20

You can test above with dummy data as below

#standardSQL
WITH all_time_series AS (
  SELECT 'a' AS time_series_name, '2016-01-01' AS dt, 1 AS value UNION ALL
  SELECT 'a', '2016-01-02', 2 UNION ALL
  SELECT 'a', '2016-01-03', 3 UNION ALL

  SELECT 'b', '2016-01-01', 1 UNION ALL
  SELECT 'b', '2016-01-02', 2 UNION ALL
  SELECT 'b', '2016-01-03', 3 UNION ALL

  SELECT 'c', '2016-01-01', 5 UNION ALL
  SELECT 'c', '2016-01-02', 6 UNION ALL
  SELECT 'c', '2016-01-03', 7 UNION ALL

  SELECT 'd', '2016-01-01', 6 UNION ALL
  SELECT 'd', '2016-01-02', 2 UNION ALL
  SELECT 'd', '2016-01-03', 3
),
series AS (
  SELECT DISTINCT time_series_name
  FROM all_time_series
),
pairs AS (
  SELECT
    series1.time_series_name AS time_series_1,
    series2.time_series_name AS time_series_2,
    CONCAT(series1.time_series_name, ' - ', series2.time_series_name) AS pair_name
  FROM series AS series1
  JOIN series AS series2
  ON series1.time_series_name < series2.time_series_name
)
SELECT pair_name, CORR(value1, value2) AS correlation
FROM (
  SELECT pair_name, a1.dt AS dt, a1.value AS value1, a2.value AS value2
  FROM pairs AS p
  JOIN all_time_series AS a1
    ON p.time_series_1 = a1.time_series_name
  JOIN all_time_series AS a2
    ON p.time_series_2 = a2.time_series_name
    AND a1.dt = a2.dt
)
GROUP BY pair_name
ORDER BY correlation DESC
LIMIT 2


问:
Sinon Stub standalone utility function in a module
I am writing a test using Sinon, the basic flow of the program is

```<code>foo(){
  return Promise.resolve(x);
}

module.exports = function (){
  ...
  foo();
  ...
}
</code>```

In my test i import the module, i want to stub foo(), is there a way i can fake the function call and return something else?

答: Actually it is a bad practice because the declared private function is a part of the module you are testing. However you can substitute any module local variable using rewire.</p>

Body:
I am writing a test using Sinon, the basic flow of the program is

foo(){
  return Promise.resolve(x);
}

module.exports = function (){
  ...
  foo();
  ...
}

In my test i import the module, i want to stub foo(), is there a way i can fake the function call and return something else?


问:
Where does the postgresql parser put the table name?
The source code has "exec_simple_query". After parsing where can the table name be found ?</p>

答: The table name is discarded in the parse phase. The parsetree just contains the oid of the table from a relcache lookup, stored in a targetlist entry. Dump the parsetree with debug_print_plans to see what I mean.