问:
Decode a prepended VarInt from a byte stream of unknown size in javascript/Nodejs
I am writing a small utility library for me to request server status of a given minecraft host in js on node. I am using the Server List Ping Protocol as outlined here (https://wiki.vg/Server_List_Ping) and got it mostly working as expected, albeit having big trouble working with unsupported Data Types (VarInt) and had to scour the internet to find a way of converting js nums into VarInts in order to craft the necessary packet buffers:

```<code>function toVarIntBuffer(integer) {
    let buffer = Buffer.alloc(0);
    while (true) {
        let tmp = integer & 0b01111111;
        integer >>>= 7;
        if (integer != 0) {
            tmp |= 0b10000000;
        }
        buffer = Buffer.concat([buffer, Buffer.from([tmp])]);
        if (integer <= 0) break;
    }
    return buffer;
}
</code>```

Right now I am able to request a server status by sending the handshake packet and then the query packet and do receive a JSON response with the length of the response prepended as a VarInt.

However the issue is here, where I simply don't know how to safely identify the VarInt from the beginning of the JSON response (as it can be anywhere up to 5 byte) and decode it back to a readable num so I can get the proper length of the response byte stream.

[...] as with all strings this is prefixed by its length as a VarInt

(from the protocol documentation)

My current super hacky workaround is to concatenate the chunks as String until the concatenated string contains the same count of '{'s and '}'s (meaning a full json object) and slice the json response at the first '{' before parsing it.

However I am very unhappy with this hacky, inefficient, unelegant and possibly unreliable way of solving the issue and would rather decode the VarInt in front of the JSON response in order to get a proper length to compare against.

答:
I don't know this protocol, but VarInt in protobuf are coded with the MSB bit:

Each byte in a varint, except the last byte, has the most significant
bit (msb) set – this indicates that there are further bytes to come.
The lower 7 bits of each byte are used to store the two's complement
representation of the number in groups of 7 bits, least significant
group first.

Note: Too long for a comment, so posting as an answer.

Update: I browsed a bit through the URL you gave, and it is indeed the ProtoBuf VarInt. It is also described there with pseudo-code:

https://wiki.vg/Protocol#VarInt_and_VarLong

VarInt and VarLong Variable-length format such that smaller numbers
use fewer bytes. These are very similar to Protocol Buffer Varints:
the 7 least significant bits are used to encode the value and the most
significant bit indicates whether there's another byte after it for
the next part of the number. The least significant group is written
first, followed by each of the more significant groups; thus, VarInts
are effectively little endian (however, groups are 7 bits, not 8).

VarInts are never longer than 5 bytes, and VarLongs are never longer
than 10 bytes.

Pseudocode to read and write VarInts and VarLongs:

Body:
I am writing a small utility library for me to request server status of a given minecraft host in js on node. I am using the Server List Ping Protocol as outlined here (https://wiki.vg/Server_List_Ping) and got it mostly working as expected, albeit having big trouble working with unsupported Data Types (VarInt) and had to scour the internet to find a way of converting js nums into VarInts in order to craft the necessary packet buffers:

function toVarIntBuffer(integer) {
    let buffer = Buffer.alloc(0);
    while (true) {
        let tmp = integer & 0b01111111;
        integer >>>= 7;
        if (integer != 0) {
            tmp |= 0b10000000;
        }
        buffer = Buffer.concat([buffer, Buffer.from([tmp])]);
        if (integer <= 0) break;
    }
    return buffer;
}

Right now I am able to request a server status by sending the handshake packet and then the query packet and do receive a JSON response with the length of the response prepended as a VarInt.

However the issue is here, where I simply don't know how to safely identify the VarInt from the beginning of the JSON response (as it can be anywhere up to 5 byte) and decode it back to a readable num so I can get the proper length of the response byte stream.

[...] as with all strings this is prefixed by its length as a VarInt

(from the protocol documentation)

My current super hacky workaround is to concatenate the chunks as String until the concatenated string contains the same count of '{'s and '}'s (meaning a full json object) and slice the json response at the first '{' before parsing it.

However I am very unhappy with this hacky, inefficient, unelegant and possibly unreliable way of solving the issue and would rather decode the VarInt in front of the JSON response in order to get a proper length to compare against.


来源: stackexchange

问:
How to retrieve a column value from DESCRIBE DETAIL <table_name>
I would like to use the "Last modified" value from the description of my table in databricks. I know how to get all columns from the table by using "DESCRIBE DETAIL table_name", but I wish to simply get the last modified value since I need to use it in my WHERE comparison</p>

答:
You can retrieve the result of the SQL query as a list and get the content like this :

spark.sql("DESCRIBE DETAIL database_name.table_name").collect()[0]['lastModified']

>>> Out[7]: datetime.datetime(2022, 2, 11, 8, 16, 5)
```

ContentLicense: CC BY-SA 4.0


问:
iOS AVFoundation: Setting Orientation of Video
I've been struggling with several dimensions to the problem of controlling video orientation during and after capture on an iOS device. Thanks to previous answers and documentation from Apple I've been able to figure it out. However, now that I want to push some video to a web site, I'm running into particular problems. I've outlined this problem in particular in this question, and the proposed solution turns out to require orientation options to be set during video encoding.

That may be, but I have no clue how to go about doing this. The documentation around setting orientation is in respect to setting it correctly for display on the device, and I've implemented the advice found here. However, this advice does not address setting the orientation properly for non-Apple software, such as VLC or the Chrome browser.

Can anyone provide insight into how to set orientation properly on the device such that it displays correctly for all viewing software?

答:
Here is the latest swift version of @Jagie code.</p>
```<code>extension AVURLAsset
{
    func exportVideo(presetName: String = AVAssetExportPresetHighestQuality, outputFileType: AVFileType = .mp4, fileExtension: String = "mp4", then completion: @escaping (URL?) -> Void)
    {
        let filename = url.deletingPathExtension().appendingPathExtension(fileExtension).lastPathComponent
        let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename)

        do { // delete old video, if already exists
                try FileManager.default.removeItem(at: outputURL)
        } catch {
            print(error.localizedDescription)
        }

        guard let sourceAudioTrack = self.tracks(withMediaType: .audio).first else { return }
        let composition = AVMutableComposition()
        let compositionAudioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
        do{
            try compositionAudioTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: self.duration), of: sourceAudioTrack, at: CMTime.zero)
        }catch(let e){
            print("error: \(e)")
        }

        if let session = AVAssetExportSession(asset: composition, presetName: presetName) {
            session.outputURL = outputURL
            session.outputFileType = outputFileType
            let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
            let range = CMTimeRangeMake(start: start, duration: duration)
            session.timeRange = range
            session.shouldOptimizeForNetworkUse = true

            session.videoComposition =  getVideoComposition(asset: self, composition: composition)

            session.exportAsynchronously {
                switch session.status {
                case .completed:
                    completion(outputURL)
                case .cancelled:
                    debugPrint("Video export cancelled.")
                    completion(nil)
                case .failed:
                    let errorMessage = session.error?.localizedDescription ?? "n/a"
                    debugPrint("Video export failed with error: \(errorMessage)")
                    completion(nil)
                default:
                    break
                }
            }
        } else {
            completion(nil)
        }
    }

    private func getVideoComposition(asset: AVAsset, composition: AVMutableComposition) -> AVMutableVideoComposition{
        let isPortrait = isVideoPortrait()

        let compositionVideoTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID:kCMPersistentTrackID_Invalid)!

        let videoTrack:AVAssetTrack = asset.tracks(withMediaType: .video).first!
        do{
        try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: videoTrack, at: CMTime.zero)
        }catch(let e){
            print("Error: \(e)")
        }

        let layerInst:AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)

        let transform = videoTrack.preferredTransform
        layerInst.setTransform(transform, at: CMTime.zero)

        let inst:AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
        inst.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: asset.duration);
        inst.layerInstructions = [layerInst]

        let videoComposition: AVMutableVideoComposition = AVMutableVideoComposition()
        videoComposition.instructions = [inst]

        var videoSize:CGSize = videoTrack.naturalSize;
        if(isPortrait) {
            print("video is portrait")
            videoSize = CGSize(width: videoSize.height, height: videoSize.width)
        }else{
            print("video is landscape")
        }

        videoComposition.renderSize = videoSize;
        videoComposition.frameDuration = CMTimeMake(value: 1,timescale: 30);
        videoComposition.renderScale = 1.0;
        return videoComposition;
    }

    func isVideoPortrait() -> Bool{
        var isPortrait = false
        let tracks = self.tracks(withMediaType: .video)
        if(tracks.count > 0) {
            let videoTrack:AVAssetTrack = tracks.first!;

            let t:CGAffineTransform = videoTrack.preferredTransform;
            // Portrait
            if(t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0)
            {
                isPortrait = true;
            }
            // PortraitUpsideDown
            if(t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0)  {

                isPortrait = true;
            }
            // LandscapeRight
            if(t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0)
            {
                isPortrait = false;
            }
            // LandscapeLeft
            if(t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0)
            {
                isPortrait = false;
            }
        }
        return isPortrait;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the latest swift version of @Jagie code.

extension AVURLAsset
{
    func exportVideo(presetName: String = AVAssetExportPresetHighestQuality, outputFileType: AVFileType = .mp4, fileExtension: String = "mp4", then completion: @escaping (URL?) -> Void)
    {
        let filename = url.deletingPathExtension().appendingPathExtension(fileExtension).lastPathComponent
        let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename)

        do { // delete old video, if already exists
                try FileManager.default.removeItem(at: outputURL)
        } catch {
            print(error.localizedDescription)
        }

        guard let sourceAudioTrack = self.tracks(withMediaType: .audio).first else { return }
        let composition = AVMutableComposition()
        let compositionAudioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
        do{
            try compositionAudioTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: self.duration), of: sourceAudioTrack, at: CMTime.zero)
        }catch(let e){
            print("error: \(e)")
        }

        if let session = AVAssetExportSession(asset: composition, presetName: presetName) {
            session.outputURL = outputURL
            session.outputFileType = outputFileType
            let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
            let range = CMTimeRangeMake(start: start, duration: duration)
            session.timeRange = range
            session.shouldOptimizeForNetworkUse = true

            session.videoComposition =  getVideoComposition(asset: self, composition: composition)

            session.exportAsynchronously {
                switch session.status {
                case .completed:
                    completion(outputURL)
                case .cancelled:
                    debugPrint("Video export cancelled.")
                    completion(nil)
                case .failed:
                    let errorMessage = session.error?.localizedDescription ?? "n/a"
                    debugPrint("Video export failed with error: \(errorMessage)")
                    completion(nil)
                default:
                    break
                }
            }
        } else {
            completion(nil)
        }
    }

    private func getVideoComposition(asset: AVAsset, composition: AVMutableComposition) -> AVMutableVideoComposition{
        let isPortrait = isVideoPortrait()

        let compositionVideoTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID:kCMPersistentTrackID_Invalid)!

        let videoTrack:AVAssetTrack = asset.tracks(withMediaType: .video).first!
        do{
        try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: videoTrack, at: CMTime.zero)
        }catch(let e){
            print("Error: \(e)")
        }

        let layerInst:AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)

        let transform = videoTrack.preferredTransform
        layerInst.setTransform(transform, at: CMTime.zero)

        let inst:AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
        inst.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: asset.duration);
        inst.layerInstructions = [layerInst]

        let videoComposition: AVMutableVideoComposition = AVMutableVideoComposition()
        videoComposition.instructions = [inst]

        var videoSize:CGSize = videoTrack.naturalSize;
        if(isPortrait) {
            print("video is portrait")
            videoSize = CGSize(width: videoSize.height, height: videoSize.width)
        }else{
            print("video is landscape")
        }

        videoComposition.renderSize = videoSize;
        videoComposition.frameDuration = CMTimeMake(value: 1,timescale: 30);
        videoComposition.renderScale = 1.0;
        return videoComposition;
    }

    func isVideoPortrait() -> Bool{
        var isPortrait = false
        let tracks = self.tracks(withMediaType: .video)
        if(tracks.count > 0) {
            let videoTrack:AVAssetTrack = tracks.first!;

            let t:CGAffineTransform = videoTrack.preferredTransform;
            // Portrait
            if(t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0)
            {
                isPortrait = true;
            }
            // PortraitUpsideDown
            if(t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0)  {

                isPortrait = true;
            }
            // LandscapeRight
            if(t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0)
            {
                isPortrait = false;
            }
            // LandscapeLeft
            if(t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0)
            {
                isPortrait = false;
            }
        }
        return isPortrait;
    }
}


问:
WPF MVVM AsyncCommand CanExecute not working
I am attempting to create a simple WPF application that have a combobox populated with server names and a button to connect to a server.

Expected behaviour:
Button is disabled at first but become avaiable as soon as a server is selected.

I am using the AsyncCommand found this in this blog post that implement the ICommand methods for Async tasks.

My problem is that the button is working properly when using normal RelayCommand but doesnt work when I use AsynCommand. Am I missing something?

Here is the simplified code:

ConnectionWindow.xaml.cs:

<ComboBox Grid.Row="1" Grid.Column="1"
             HorizontalAlignment="Left"
             x:Name="listSourceServer"
             ItemsSource="{Binding ListSourceServer}"
             SelectedValue="{Binding SelectedSourceServer}"
             VerticalAlignment="Top"
             Width="450"
             RenderTransformOrigin="0.5,0.5"/>

<Button Grid.Row="1" Grid.Column="2"
            Content="Connect"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="100"
            Height="25"
            FontFamily="Arial"
            Foreground="#FFFFFF"
            Background="#2e86de"
            Command="{Binding ButtonConnectSourceServer}">
    </Button>
```
<p><strong>ConnectionViewModel.cs:</strong></p>
```private string _selectedSourceServer;
public string SelectedSourceServer
    {
        set
        {
            _selectedSourceServer = value;
            OnPropertyChanged(nameof(SelectedSourceServer));
        }
        get => _selectedSourceServer;
    }
private async Task ConnectSourceServerAsync()
    {
        await ConnectAsync(SelectedSourceServer);
    }

    private bool CanConnectOnSourceServer()
    {
        return !string.IsNullOrEmpty(SelectedSourceServer);
    }

public ConnectionViewModel() {
    ButtonConnectSourceServer = new AsyncCommand(ConnectSourceServerAsync, CanConnectOnSourceServer);
}
```
<p><strong>AsyncCommand.cs:</strong></p>
```    public interface IAsyncCommand : ICommand
{
    Task ExecuteAsync();
    bool CanExecute();
}

public class AsyncCommand : IAsyncCommand
{
    public event EventHandler CanExecuteChanged;

    private bool _isExecuting;
    private readonly Func<Task> _execute;
    private readonly Func<bool> _canExecute;
    private readonly IErrorHandler _errorHandler;

    public AsyncCommand(
        Func<Task> execute,
        Func<bool> canExecute = null,
        IErrorHandler errorHandler = null)
    {
        _execute = execute;
        _canExecute = canExecute;
        _errorHandler = errorHandler;
    }

    public bool CanExecute()
    {
        return !_isExecuting && (_canExecute?.Invoke() ?? true);
    }

    public async Task ExecuteAsync()
    {
        if (CanExecute())
        {
            try
            {
                _isExecuting = true;
                await _execute();
            }
            finally
            {
                _isExecuting = false;
            }
        }

        RaiseCanExecuteChanged();
    }

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }

    #region Explicit implementations
    bool ICommand.CanExecute(object parameter)
    {
        return CanExecute();
    }

    void ICommand.Execute(object parameter)
    {
        ExecuteAsync().FireAndForgetSafeAsync(_errorHandler);
    }
    #endregion
}
```

答:
You need to call the RaiseCanExecuteChanged method when the SelectedSourceServer property changes.

```<code>public ConnectionViewModel()
{
    _buttonConnectSourceServer = new AsyncCommand(ConnectSourceServerAsync, CanConnectOnSourceServer);
}

private readonly AsyncCommand _buttonConnectSourceServer;
public IAsyncCommand ButtonConnectSourceServer => _buttonConnectSourceServer;

private string _selectedSourceServer;
public string SelectedSourceServer
{
    get => _selectedSourceServer;
    set
    {
        _selectedSourceServer = value;
        OnPropertyChanged(nameof(SelectedSourceServer));
        _buttonConnectSourceServer.RaiseCanExecuteChanged();
    }
}
</code>```

Body:
I am attempting to create a simple WPF application that have a combobox populated with server names and a button to connect to a server.

Expected behaviour:
Button is disabled at first but become avaiable as soon as a server is selected.

I am using the AsyncCommand found this in this blog post that implement the ICommand methods for Async tasks.

My problem is that the button is working properly when using normal RelayCommand but doesnt work when I use AsynCommand. Am I missing something?

Here is the simplified code:

ConnectionWindow.xaml.cs:

<ComboBox Grid.Row="1" Grid.Column="1"
             HorizontalAlignment="Left"
             x:Name="listSourceServer"
             ItemsSource="{Binding ListSourceServer}"
             SelectedValue="{Binding SelectedSourceServer}"
             VerticalAlignment="Top"
             Width="450"
             RenderTransformOrigin="0.5,0.5"/>

<Button Grid.Row="1" Grid.Column="2"
            Content="Connect"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="100"
            Height="25"
            FontFamily="Arial"
            Foreground="#FFFFFF"
            Background="#2e86de"
            Command="{Binding ButtonConnectSourceServer}">
    </Button>

ConnectionViewModel.cs:

private string _selectedSourceServer;
public string SelectedSourceServer
    {
        set
        {
            _selectedSourceServer = value;
            OnPropertyChanged(nameof(SelectedSourceServer));
        }
        get => _selectedSourceServer;
    }
private async Task ConnectSourceServerAsync()
    {
        await ConnectAsync(SelectedSourceServer);
    }

    private bool CanConnectOnSourceServer()
    {
        return !string.IsNullOrEmpty(SelectedSourceServer);
    }

public ConnectionViewModel() {
    ButtonConnectSourceServer = new AsyncCommand(ConnectSourceServerAsync, CanConnectOnSourceServer);
}

AsyncCommand.cs:

    public interface IAsyncCommand : ICommand
{
    Task ExecuteAsync();
    bool CanExecute();
}

public class AsyncCommand : IAsyncCommand
{
    public event EventHandler CanExecuteChanged;

    private bool _isExecuting;
    private readonly Func<Task> _execute;
    private readonly Func<bool> _canExecute;
    private readonly IErrorHandler _errorHandler;

    public AsyncCommand(
        Func<Task> execute,
        Func<bool> canExecute = null,
        IErrorHandler errorHandler = null)
    {
        _execute = execute;
        _canExecute = canExecute;
        _errorHandler = errorHandler;
    }

    public bool CanExecute()
    {
        return !_isExecuting && (_canExecute?.Invoke() ?? true);
    }

    public async Task ExecuteAsync()
    {
        if (CanExecute())
        {
            try
            {
                _isExecuting = true;
                await _execute();
            }
            finally
            {
                _isExecuting = false;
            }
        }

        RaiseCanExecuteChanged();
    }

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }

    #region Explicit implementations
    bool ICommand.CanExecute(object parameter)
    {
        return CanExecute();
    }

    void ICommand.Execute(object parameter)
    {
        ExecuteAsync().FireAndForgetSafeAsync(_errorHandler);
    }
    #endregion
}

Body:
You need to call the RaiseCanExecuteChanged method when the SelectedSourceServer property changes.

public ConnectionViewModel()
{
    _buttonConnectSourceServer = new AsyncCommand(ConnectSourceServerAsync, CanConnectOnSourceServer);
}

private readonly AsyncCommand _buttonConnectSourceServer;
public IAsyncCommand ButtonConnectSourceServer => _buttonConnectSourceServer;

private string _selectedSourceServer;
public string SelectedSourceServer
{
    get => _selectedSourceServer;
    set
    {
        _selectedSourceServer = value;
        OnPropertyChanged(nameof(SelectedSourceServer));
        _buttonConnectSourceServer.RaiseCanExecuteChanged();
    }
}


问:
How to use Subquery which returned more than one result
My SQL query

```<code>UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)
</code>```

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

答:
How about the following. You can use simple joins the same way you do in SELECT statements:</p>

```<code>UPDATE Task t, User u
SET t.Done = 1
WHERE t.ID = u.ID
AND u.UserName = @UserName
</code>```

Body:
My SQL query

UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

Body:
How about the following. You can use simple joins the same way you do in SELECT statements:

UPDATE Task t, User u
SET t.Done = 1
WHERE t.ID = u.ID
AND u.UserName = @UserName


问:
Calculate Stoploss Percentage in Pinescript
I know how to get the calculate the stoploss 245.6 but I don't know how to get the percentage 2.08% ... Can someone please help me get the formula for the percentage?

I used the following formula to get the stoploss 245.6 pips

```<code>pips = (abs(1.18047 - 1.15591) / syminfo.mintick) / 10
</code>```

答:
The percentage formula can be written in different forms, it is essentially an algebraic equation involving three values that you can turn into a function, for example:</p>
```<code>//@version=5
indicator("", format = format.percent)

percent(value1, value2) => float(value1)/float(value2) * 100

val1 = 1.15591
val2 = 1.18047

percentChange = 100 - percent(val1, val2)

plot(percentChange) // 2.08
</code>```

Body:
I know how to get the calculate the stoploss 245.6 but I don't know how to get the percentage 2.08% ... Can someone please help me get the formula for the percentage?

I used the following formula to get the stoploss 245.6 pips

pips = (abs(1.18047 - 1.15591) / syminfo.mintick) / 10

Body:
The percentage formula can be written in different forms, it is essentially an algebraic equation involving three values that you can turn into a function, for example:

//@version=5
indicator("", format = format.percent)

percent(value1, value2) => float(value1)/float(value2) * 100

val1 = 1.15591
val2 = 1.18047

percentChange = 100 - percent(val1, val2)

plot(percentChange) // 2.08


问:
Cannot find the fallback endpoint specified by route values: { page: /_Host, area: }
I use This Project and created a project exactly like it, But receive

Cannot find the fallback endpoint specified by route values: { page: /_Host, area: }.

Error when I start the project, In the startup configure method I have:

```<code> app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapDefaultControllerRoute();
                endpoints.MapFallbackToPage("/_Host");
            });
</code>```

How to resolve this error?

答:
.NET6, in your csproj file make sure you use Web SDK.

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
</code>```

Also, add this to your property group:

```<code>  <PropertyGroup>
     <UseRazorSourceGenerator>false</UseRazorSourceGenerator>
  </PropertyGroup>
</code>```

Body:
I use This Project and created a project exactly like it, But receive

Cannot find the fallback endpoint specified by route values: { page: /_Host, area: }.

Error when I start the project, In the startup configure method I have:

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapDefaultControllerRoute();
                endpoints.MapFallbackToPage("/_Host");
            });

How to resolve this error?

Body:
.NET6, in your csproj file make sure you use Web SDK.

<Project Sdk="Microsoft.NET.Sdk.Web">

Also, add this to your property group:

  <PropertyGroup>
     <UseRazorSourceGenerator>false</UseRazorSourceGenerator>
  </PropertyGroup>


问:
Does anyone know nay fix for this error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>'
In local working fine but when i deployed on digital ocean Kubernetes server then showing error. please help....

答:
This is not a kubernetes specific issue. Kubernetes is a docker orchestrator. So you have to modify your dockerfile to use a working node base image.

Also I would recommend to you to not use odd major versions of node, as they are bleeding edge. Best practice is to use LTS-versions for production, to specifically avoid such issues, and those are node versions with even major-version (12, 14, 16...).

If you use node:latest in your dockerfile, than you are using node 17.5, according to dockerhub. And thats why you have issues.

Best practice for node docker images is to pinpoint exact versions down to patch-version. E.g. use 16.14.0-alpine3.15 instead of 16-alpine. Thus also avoiding caching an old node 16 base image in docker and then wondering why you building on a different machine breaks.

https://github.com/Automattic/mongoose/issues/11377


问:
Oracle Database connection from Eclipse not working
Eclipse Version: Neon.3 Release (4.6.3)

On New Database Connection Profile/Wizard, I select Oracle as Database Type add ojdbc 8 jar and enter requested details for Oracle instance running on remote server.

I enter server, port and service values as I enter in SQL Developer (where I am able to connect), but connection test never succeed from Eclipse.

Once values are entered it constructs JDBC URL (which is not editable) in below format:
jdbc:oracle:thin:@server:port:service

Error message:
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

Though I wanted to directly provide jdbc URL "Connection URL" field is not editable.

答:
After some more digging found it in one of Eclipse bug reports. Thanks to Mike Hatherly for workaround, reference: https://bugs.eclipse.org/bugs/show_bug.cgi?id=382063#c3

Work around provided by Mike Hatherly:
"I have found a workaround. If you export the Database connection details, you can then manually edit the property org.eclipse.datatools.connectivity.db.URL to include the missing '/'s, then re-import and overwrite the current connection. Doing this however shows the connection properties in Eclipse as missing values, although the connection works correctly."

So before exporting you would 've saved connection profile with password and everything and Export un-encrypted. And the correct URL format when using ServiceName: jdbc:oracle:thin:@//server:port/ServiceName


问:
How to filter an associative arrays using array of keys in PHP?
I have an associative arrays and an array of keys.

```<code>$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');
</code>```

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

```<code>$C = array('a'=>'book', 'b'=>'pencil');
</code>```

答:
```<code>$keys = array_flip($B);
$C = array_intersect_key($A,$keys);
</code>```

Body:
I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');


问:
How to make spring accept multiple synchronous requests?
I am implementing a system using Spring Boot 2.3.5 where two micro-services (e.g. A and B) make web requests to each other in a way like this:

Service A -> Service B -> Service A

This services are hosted in Azure App Services, where this type of flow works with no problem at all.

The problem is when running locally, the second call from Service B to Service A causes a deadlock, once the Service A is waiting for the service B to respond, causing a timeout exception.

My question is: Is there a way to make Spring Boot applications accept more than one request simultaneously while running on local machine?

I've already tried to set the variable server.tomcat.threads.max to 100 in the application-local.yml from the Service A but with no success.

答:
As pointed out by M. Deinum the reason of the deadlock was a block in the database caused by the @Transactional annotation.

The problem was that during the second call to Service A the spring was trying to access a table which spring blocked because of the transactional.

What I did was take out the first call from the transactional method and place it in another use case, therefore when Service A tries to read the value, the table is already free.


问:
How can i create environment in python?
My project has an python version(3.10),i want to add python (3.6) version.
i dont want to delete the old version and my pc has not enough space for virtual machine.
How can i create env?
Can anyone help? Python was first installed directly, should I install anaconda?</p>

答:
If you wish to use different versions of python you can use tools such as asfd which will allow you to install as using different versions by switching in the terminal.

https://asdf-vm.com/guide/getting-started.html#_6-set-a-version

Title: How can i create environment in python?


问:
Access violation error when trying to free an array
I'm currently working on structures for a personnal project. I'm trying to use dynamically-allocated bidimensionnal arrays, and then free the space they're taking. An error occurs when I try to free the allocated space.

I was able to narrow down the source of the issue down to the function I had set up to destroy my structures, but wasn't able to pinpoint the cause of the error within. More concerning is the fact that the error, an access violation, only triggers half of the time.
I've included the functions below, with a few comments. I'm sorry if I'm including too much code here, but I'm geniunely lost at words and do feel like the way I initialize the structures may have an impact on whether I'm destroying them correctly.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct f_part f_part;
typedef struct field field;

//these are the structures I used:
//part of a field: includes a character and a color
struct f_part
{
    char caractere;
    short int color;
};

//field: points to a bidimensionnal array of f_part, and remember its size
struct field
{
    int fsize_x;
    int fsize_y;
    f_part **fbody;
};

field* fieldInitialize(const int size_x, const int size_y)  //this function seems to work correctly, I've mostly added it as an indicator
{
    field* terrain = malloc(sizeof(*terrain));
    if (terrain == NULL)
        printf("fail1");
    terrain->fsize_x = size_x;
    terrain->fsize_y = size_y;
    f_part* ptrToFPart = NULL;
    terrain->fbody = malloc(sizeof(ptrToFPart) * size_x);   //this is where I allocate the space for an array of pointers
    if (terrain->fbody == NULL)
        printf("fail2");

    int i,j;
    for (i = 0 ; i < size_x ; i++)
    {
        terrain->fbody[i] = malloc(sizeof(f_part) * size_y);
        for (j = 0 ; j < size_y ; j++)
        {
            terrain->fbody[i][j].caractere = 'a';
            terrain->fbody[i][j].color = 0;
        }
    }
    terrain->fsize_x = size_x;
    terrain->fsize_y = size_y;
    return terrain;
}

void fieldDestroy(field* terrain)   //this is the function that is supposed to destroy the object and free the memory, and fails
{
    int i;
    for (i = 0 ; i < terrain->fsize_x ; i++)
    {
        free(terrain->fbody[i]);    //this part always goes well
    }
    printf("flag 1\n");
    free(terrain->fbody);   //this is where the access violation happens, when it does
    printf("flag 2\n");
    free(terrain);      //this part goes well too
    printf("flag 3\n");
}

int main()
{
    field* testField = fieldInitialize(5, 5);
    fieldDestroy(testField);       //This is the function that fails. Sometimes.
return 0;
}

</code>```

The error systematically happens on that second-to-last line, when I try to free the space allocated for the array of pointers. Except it doesn't always happen! Sometimes, I can free terrain->fbody, and everything goes well, but other times, I can't free the space.
The error I get is 0xC0000005, which apparently translates to "access violation". Which I understand would be common when dealing with dynamic memory allocation, but then why do I seem to get the error only half of the time?

Edit : Okay, so I've edited a bit of the code. Interestingly enough, while my Windows 10 would fail between flags 1 and 2, my Windows 7 fails between flags 2 and 3, and returns too a 0xC0000005 error. But again, only occasionally.

答:
In C, you must precede structure names with struct.  So your functions should be declared:

```<code>struct field* fieldInitialize( ... )
</code>```

and your allocations should be

```<code>struct field* terrain = malloc(sizeof(struct field));
</code>```

You could also define these structures as types:

```<code>typedef struct
{
    int fsize_x;
    int fsize_y;
    struct f_part **fbody;
} field;
</code>```

Body:
I'm currently working on structures for a personnal project. I'm trying to use dynamically-allocated bidimensionnal arrays, and then free the space they're taking. An error occurs when I try to free the allocated space.

I was able to narrow down the source of the issue down to the function I had set up to destroy my structures, but wasn't able to pinpoint the cause of the error within. More concerning is the fact that the error, an access violation, only triggers half of the time.
I've included the functions below, with a few comments. I'm sorry if I'm including too much code here, but I'm geniunely lost at words and do feel like the way I initialize the structures may have an impact on whether I'm destroying them correctly.

#include <stdio.h>
#include <stdlib.h>

typedef struct f_part f_part;
typedef struct field field;

//these are the structures I used:
//part of a field: includes a character and a color
struct f_part
{
    char caractere;
    short int color;
};

//field: points to a bidimensionnal array of f_part, and remember its size
struct field
{
    int fsize_x;
    int fsize_y;
    f_part **fbody;
};

field* fieldInitialize(const int size_x, const int size_y)  //this function seems to work correctly, I've mostly added it as an indicator
{
    field* terrain = malloc(sizeof(*terrain));
    if (terrain == NULL)
        printf("fail1");
    terrain->fsize_x = size_x;
    terrain->fsize_y = size_y;
    f_part* ptrToFPart = NULL;
    terrain->fbody = malloc(sizeof(ptrToFPart) * size_x);   //this is where I allocate the space for an array of pointers
    if (terrain->fbody == NULL)
        printf("fail2");

    int i,j;
    for (i = 0 ; i < size_x ; i++)
    {
        terrain->fbody[i] = malloc(sizeof(f_part) * size_y);
        for (j = 0 ; j < size_y ; j++)
        {
            terrain->fbody[i][j].caractere = 'a';
            terrain->fbody[i][j].color = 0;
        }
    }
    terrain->fsize_x = size_x;
    terrain->fsize_y = size_y;
    return terrain;
}

void fieldDestroy(field* terrain)   //this is the function that is supposed to destroy the object and free the memory, and fails
{
    int i;
    for (i = 0 ; i < terrain->fsize_x ; i++)
    {
        free(terrain->fbody[i]);    //this part always goes well
    }
    printf("flag 1\n");
    free(terrain->fbody);   //this is where the access violation happens, when it does
    printf("flag 2\n");
    free(terrain);      //this part goes well too
    printf("flag 3\n");
}

int main()
{
    field* testField = fieldInitialize(5, 5);
    fieldDestroy(testField);       //This is the function that fails. Sometimes.
return 0;
}

The error systematically happens on that second-to-last line, when I try to free the space allocated for the array of pointers. Except it doesn't always happen! Sometimes, I can free terrain->fbody, and everything goes well, but other times, I can't free the space.
The error I get is 0xC0000005, which apparently translates to "access violation". Which I understand would be common when dealing with dynamic memory allocation, but then why do I seem to get the error only half of the time?

Edit : Okay, so I've edited a bit of the code. Interestingly enough, while my Windows 10 would fail between flags 1 and 2, my Windows 7 fails between flags 2 and 3, and returns too a 0xC0000005 error. But again, only occasionally.

Body:
In C, you must precede structure names with struct.  So your functions should be declared:

struct field* fieldInitialize( ... )

and your allocations should be

struct field* terrain = malloc(sizeof(struct field));

You could also define these structures as types:

typedef struct
{
    int fsize_x;
    int fsize_y;
    struct f_part **fbody;
} field;


问:
Best way to handle conditional parent containers in React?
Let's say I have two different styles for a component, one that is flat, and one that is floating/rounded. The floating/rounded one requires an extra div wrapping (li provides a little padding, div gets extra 'float styles'). The styles aren't that important, but here is the solution I've come to that requires the least amount of code:

```<code>const Parent = ({variant}) => {
const child = [<p>The children go here!</p>]

if (variant === "rounded") {
 return (
      <Rounded>
          {child}
      </Rounded>
  )
} else {
 return (
      <Flat>
          {child}
      </Flat>
  )
}

const Rounded = ({ children }) => {
  const classes = useStyles();
  return (
    <li className={`${classes.li} ${classes.li_rounded}`}>
      <div className={classes.div}>{children}</div>
    </li>
  );
};

const Flat = ({ children }) => {
  const classes = useStyles();
  return (
    <li
      className={`${classes.li} ${classes.li_flat}`}
    >
      {children}
    </li>
  );
};
</code>```

Is this the best way to do this with the most minimal amount of code? I can't seem to find a better solution. The code can still end up being quite long if the "wrapper" components/elements themselves require multiple props (then I'm writing a bunch of repetitive code relating to the props, and repetition is the reason why I'm doing this).

答:
You could do</p>
```<code>const Container = variant === 'rounded' ? Rounded : Flat;

return <Container>{child}</Container>
</code>```

Body:
Let's say I have two different styles for a component, one that is flat, and one that is floating/rounded. The floating/rounded one requires an extra div wrapping (li provides a little padding, div gets extra 'float styles'). The styles aren't that important, but here is the solution I've come to that requires the least amount of code:

const Parent = ({variant}) => {
const child = [
The children go here!
]

if (variant === "rounded") {
 return (
      <Rounded>
          {child}
      </Rounded>
  )
} else {
 return (
      <Flat>
          {child}
      </Flat>
  )
}

const Rounded = ({ children }) => {
  const classes = useStyles();
  return (
    <li className={`${classes.li} ${classes.li_rounded}`}>

{children}

  );
};

const Flat = ({ children }) => {
  const classes = useStyles();
  return (
    <li
      className={`${classes.li} ${classes.li_flat}`}
    >
      {children}

  );
};

Is this the best way to do this with the most minimal amount of code? I can't seem to find a better solution. The code can still end up being quite long if the "wrapper" components/elements themselves require multiple props (then I'm writing a bunch of repetitive code relating to the props, and repetition is the reason why I'm doing this).

Body:
You could do

const Container = variant === 'rounded' ? Rounded : Flat;

return <Container>{child}</Container>


问:
Sending an email from Ktor server running on VPS
I am trying to send an email from a Ktor application.
When the following code is running on localhost it works fine

```<code> val responseEmail = SimpleEmail()
        responseEmail.hostName = "smtp.googlemail.com"
        responseEmail.setSmtpPort(465)
        responseEmail.setAuthenticator(DefaultAuthenticator("email@gmail.com", "pass"))
        responseEmail.isSSLOnConnect = true
        responseEmail.setFrom("email@gmail.com")
        responseEmail.subject = "Subject"
        responseEmail.setMsg("msg")
        responseEmail.addTo(email)
        responseEmail.send()
</code>```

Even if I set responseEmail.isSSLOnConnect = false still does not work
But when I run the application on a VPS (doesn't have SSL), I get the following exception:

```<code>org.apache.commons.mail.EmailException: Sending the email to the following server failed: smtp.googlemail.com:465
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1469)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.send(Email.java:1496)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.data.modules.AccountManagementModule.forgottenPassword(AccountManagementModu>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invokeSuspend(Account>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invoke(AccountManagem>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invoke(AccountManagem>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing.executeResult(Routing.kt:151)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing.interceptor(Routing.kt:35)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:103)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing$Feature$install$1.invoke(Routing.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.ContentNegotiation$Feature$install$1.invokeSuspend(ContentNegotiation.kt:110)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.ContentNegotiation$Feature$install$1.invoke(ContentNegotiation.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.CallLogging$Feature$install$2.invokeSuspend(CallLogging.kt:139)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.CallLogging$Feature$install$2.invoke(CallLogging.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invokeSuspend(DefaultEnginePipeline>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invoke(DefaultEnginePipeline.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandle>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:55)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:112)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler.handleRequest(NettyApplicationCallHandler.kt:43)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler.channelRead(NettyApplicationCallHandler.kt:34)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.EventLoopGroupProxy$Companion$create$factory$1$1.run(NettyApplicationEngine.kt:216)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at java.lang.Thread.run(Thread.java:748)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 4-yJLa62muQ6uc6fMiBsu1s3xvCVFPJMWkV7YJdO-ZDZWOwlDsYdqEJjjq0uadKzohvM1
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 56A4kwN7LQ9Sg-98Z2lpmlz7gz5ozvN6E4A-kQJ2U_Kk79iX5ziUZy503ETUA2-J>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 Please log in via your web browser and then try again.
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14  Learn more at
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534 5.7.14  https://support.google.com/mail/answer/78754 ay38sm4917546wmb.3 - gsmtp
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:932)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:843)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:748)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:388)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:246)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:195)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Transport.send0(Transport.java:254)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Transport.send(Transport.java:124)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1459)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         ... 51 common frames omitted
</code>```

How can I fix this? Is there a way to send an email from Ktor server running on a VPS without SSL.

Things I have done:
I tried using a different port: 465, 587
I have enabled less secure apps

答: Solution: Authorize access for your IP or client machine using the https://accounts.google.com/DisplayUnlockCaptcha link. That can resolve authentication issues.</p>

Body:
I am trying to send an email from a Ktor application.
When the following code is running on localhost it works fine

 val responseEmail = SimpleEmail()
        responseEmail.hostName = "smtp.googlemail.com"
        responseEmail.setSmtpPort(465)
        responseEmail.setAuthenticator(DefaultAuthenticator("email@gmail.com", "pass"))
        responseEmail.isSSLOnConnect = true
        responseEmail.setFrom("email@gmail.com")
        responseEmail.subject = "Subject"
        responseEmail.setMsg("msg")
        responseEmail.addTo(email)
        responseEmail.send()

Even if I set responseEmail.isSSLOnConnect = false still does not work
But when I run the application on a VPS (doesn't have SSL), I get the following exception:

org.apache.commons.mail.EmailException: Sending the email to the following server failed: smtp.googlemail.com:465
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1469)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.send(Email.java:1496)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.data.modules.AccountManagementModule.forgottenPassword(AccountManagementModu>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invokeSuspend(Account>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invoke(AccountManagem>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at eu.bbsapps.forgottenfilmsapi.routes.AccountManagementKt$accountManagementRoute$11$1.invoke(AccountManagem>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing.executeResult(Routing.kt:151)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing.interceptor(Routing.kt:35)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:103)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.routing.Routing$Feature$install$1.invoke(Routing.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.ContentNegotiation$Feature$install$1.invokeSuspend(ContentNegotiation.kt:110)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.ContentNegotiation$Feature$install$1.invoke(ContentNegotiation.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.CallLogging$Feature$install$2.invokeSuspend(CallLogging.kt:139)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.features.CallLogging$Feature$install$2.invoke(CallLogging.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invokeSuspend(DefaultEnginePipeline>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$2.invoke(DefaultEnginePipeline.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:243)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:113)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:133)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandle>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:55)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:112)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler.handleRequest(NettyApplicationCallHandler.kt:43)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.NettyApplicationCallHandler.channelRead(NettyApplicationCallHandler.kt:34)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.ktor.server.netty.EventLoopGroupProxy$Companion$create$factory$1$1.run(NettyApplicationEngine.kt:216)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at java.lang.Thread.run(Thread.java:748)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 4-yJLa62muQ6uc6fMiBsu1s3xvCVFPJMWkV7YJdO-ZDZWOwlDsYdqEJjjq0uadKzohvM1
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 56A4kwN7LQ9Sg-98Z2lpmlz7gz5ozvN6E4A-kQJ2U_Kk79iX5ziUZy503ETUA2-J>
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14 Please log in via your web browser and then try again.
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534-5.7.14  Learn more at
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]: 534 5.7.14  https://support.google.com/mail/answer/78754 ay38sm4917546wmb.3 - gsmtp
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:932)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:843)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:748)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:388)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:246)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Service.connect(Service.java:195)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Transport.send0(Transport.java:254)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at javax.mail.Transport.send(Transport.java:124)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1459)
Feb 11 11:20:53 ubuntu-s-1vcpu-1gb-fra1-01 java[737632]:         ... 51 common frames omitted

How can I fix this? Is there a way to send an email from Ktor server running on a VPS without SSL.

Things I have done:
I tried using a different port: 465, 587
I have enabled less secure apps


问:
Difference between priority queue and a heap
It seems that a priority queue is just a heap with normal queue operations like insert, delete, top, etc. Is this the correct way to interpret a priority queue? I know you can build priority queues in different ways but if I were to build a priority queue from a heap is it necessary to create a priority queue class and give instructions for building a heap and the queue operations or is it not really necessary to build the class?

What I mean is if I have a function to build a heap and functions to do operations like insert and delete, do I need to put all these functions in a class or can I just use the instructions by calling them in main.

I guess my question is whether having a collection of functions is equivalent to storing them in some class and using them through a class or just using the functions themselves.

What I have below is all the methods for a priority queue implementation. Is this sufficient to call it an implementation or do I need to put it in a designated priority queue class?

```<code>#ifndef MAX_PRIORITYQ_H
#define MAX_PRIORITYQ_H
#include <iostream>
#include <deque>
#include "print.h"
#include "random.h"

int parent(int i)
{
    return (i - 1) / 2;
}

int left(int i)
{
    if(i == 0)
        return 1;
    else
        return 2*i;
}

int right(int i)
{
    if(i == 0)
        return 2;
    else
        return 2*i + 1;
}

void max_heapify(std::deque<int> &A, int i, int heapsize)
{
    int largest;
    int l = left(i);
    int r = right(i);
    if(l <= heapsize && A[l] > A[i])
        largest = l;
    else
        largest = i;
    if(r <= heapsize && A[r] > A[largest])
        largest = r;
    if(largest != i) {
        exchange(A, i, largest);
        max_heapify(A, largest, heapsize);
        //int j = max_heapify(A, largest, heapsize);
        //return j;
    }
    //return i;
}

void build_max_heap(std::deque<int> &A)
{
    int heapsize = A.size() - 1;
    for(int i = (A.size() - 1) / 2; i >= 0; i--)
        max_heapify(A, i, heapsize);
}

int heap_maximum(std::deque<int> &A)
{
    return A[0];
}

int heap_extract_max(std::deque<int> &A, int heapsize)
{
    if(heapsize < 0)
        throw std::out_of_range("heap underflow");
    int max = A.front();
    //std::cout << "heapsize : " << heapsize << std::endl;
    A[0] = A[--heapsize];
    A.pop_back();
    max_heapify(A, 0, heapsize);
    //int i = max_heapify(A, 0, heapsize);
    //A.erase(A.begin() + i);
    return max;
}

void heap_increase_key(std::deque<int> &A, int i, int key)
{
    if(key < A[i])
        std::cerr << "New key is smaller than current key" << std::endl;
    else {
        A[i] = key;
        while(i > 1 && A[parent(i)] < A[i]) {
            exchange(A, i, parent(i));
            i = parent(i);
        }
    }
}

void max_heap_insert(std::deque<int> &A, int key)
{
    int heapsize =  A.size();
    A[heapsize] = std::numeric_limits<int>::min();
    heap_increase_key(A, heapsize, key);
}
</code>```

答:
A priority queue is an abstract data structure that can be implemented in many ways-unsorted array,sorted array,heap-. It is like an interface, it gives you the signature of heap:

```<code>class PriorityQueue {
   top() → element
   peek() → element
   insert(element, priority)
   remove(element)
   update(element, newPriority)
   size() → int
}
</code>```

A heap is a concrete implementation of the priority queue using an array (it can conceptually be represented as a particular kind of binary tree) to hold elements and specific algorithms to enforce invariants. Invariants are internal properties that always hold true throughout the life of the data structure.

here is the performance comparison of priority queue implementions:

Body:
It seems that a priority queue is just a heap with normal queue operations like insert, delete, top, etc. Is this the correct way to interpret a priority queue? I know you can build priority queues in different ways but if I were to build a priority queue from a heap is it necessary to create a priority queue class and give instructions for building a heap and the queue operations or is it not really necessary to build the class?

What I mean is if I have a function to build a heap and functions to do operations like insert and delete, do I need to put all these functions in a class or can I just use the instructions by calling them in main.

I guess my question is whether having a collection of functions is equivalent to storing them in some class and using them through a class or just using the functions themselves.

What I have below is all the methods for a priority queue implementation. Is this sufficient to call it an implementation or do I need to put it in a designated priority queue class?

#ifndef MAX_PRIORITYQ_H
#define MAX_PRIORITYQ_H
#include <iostream>
#include <deque>
#include "print.h"
#include "random.h"

int parent(int i)
{
    return (i - 1) / 2;
}

int left(int i)
{
    if(i == 0)
        return 1;
    else
        return 2*i;
}

int right(int i)
{
    if(i == 0)
        return 2;
    else
        return 2*i + 1;
}

void max_heapify(std::deque<int> &A, int i, int heapsize)
{
    int largest;
    int l = left(i);
    int r = right(i);
    if(l <= heapsize && A[l] > A[i])
        largest = l;
    else
        largest = i;
    if(r <= heapsize && A[r] > A[largest])
        largest = r;
    if(largest != i) {
        exchange(A, i, largest);
        max_heapify(A, largest, heapsize);
        //int j = max_heapify(A, largest, heapsize);
        //return j;
    }
    //return i;
}

void build_max_heap(std::deque<int> &A)
{
    int heapsize = A.size() - 1;
    for(int i = (A.size() - 1) / 2; i >= 0; i--)
        max_heapify(A, i, heapsize);
}

int heap_maximum(std::deque<int> &A)
{
    return A[0];
}

int heap_extract_max(std::deque<int> &A, int heapsize)
{
    if(heapsize < 0)
        throw std::out_of_range("heap underflow");
    int max = A.front();
    //std::cout << "heapsize : " << heapsize << std::endl;
    A[0] = A[--heapsize];
    A.pop_back();
    max_heapify(A, 0, heapsize);
    //int i = max_heapify(A, 0, heapsize);
    //A.erase(A.begin() + i);
    return max;
}

void heap_increase_key(std::deque<int> &A, int i, int key)
{
    if(key < A[i])
        std::cerr << "New key is smaller than current key" << std::endl;
    else {
        A[i] = key;
        while(i > 1 && A[parent(i)] < A[i]) {
            exchange(A, i, parent(i));
            i = parent(i);
        }
    }
}

void max_heap_insert(std::deque<int> &A, int key)
{
    int heapsize =  A.size();
    A[heapsize] = std::numeric_limits<int>::min();
    heap_increase_key(A, heapsize, key);
}

Body:
A priority queue is an abstract data structure that can be implemented in many ways-unsorted array,sorted array,heap-. It is like an interface, it gives you the signature of heap:

class PriorityQueue {
   top() → element
   peek() → element
   insert(element, priority)
   remove(element)
   update(element, newPriority)
   size() → int
}

A heap is a concrete implementation of the priority queue using an array (it can conceptually be represented as a particular kind of binary tree) to hold elements and specific algorithms to enforce invariants. Invariants are internal properties that always hold true throughout the life of the data structure.

here is the performance comparison of priority queue implementions:


问:
How to create random number in ifelse function?
I would like to implement random numbers for the time values equal to 0 (time == 0) and keep other time values as given.

```<code>set.seed(123)
 df$time.new <- ifelse(df$time == 0, sample(0.2:0.8, replace=F), df$time)
</code>```

Using the formula only 0.2 is created.

答:
I will fill the blanks in the comment that answered the question.  This is your code:

```<code>set.seed(123)
 df$time.new <- ifelse(df$time == 0, sample(0.2:0.8, replace=F), df$time)
</code>```

The key to understand why you are getting always 0.2 is to run:

```<code>0.2:0.8
</code>```

This just yields: [1] 0.2 and that's the reason you are always getting 0.2  The seq() command lets you make sequences that have more elements by specifying shorter increments:

```<code>> seq(0.2, 0.8, by = 0.1)
[1] 0.2 0.3 0.4 0.5 0.6 0.7 0.8
</code>```

If I remember correctly the default increment for a:b is one unit.  Let's check a toy example:

```<code>> a <- 1; b <- 7
> a:b
[1] 1 2 3 4 5 6 7
</code>```

If we do this with a <- 0.2 and b <- 0.8 the resulting vector would consist of just the value 0.2 hence, your code just detects such value.

Body:
I would like to implement random numbers for the time values equal to 0 (time == 0) and keep other time values as given.

set.seed(123)
 df$time.new <- ifelse(df$time == 0, sample(0.2:0.8, replace=F), df$time)

Using the formula only 0.2 is created.

Body:
I will fill the blanks in the comment that answered the question.  This is your code:

set.seed(123)
 df$time.new <- ifelse(df$time == 0, sample(0.2:0.8, replace=F), df$time)

The key to understand why you are getting always 0.2 is to run:

0.2:0.8

This just yields: [1] 0.2 and that's the reason you are always getting 0.2  The seq() command lets you make sequences that have more elements by specifying shorter increments:

> seq(0.2, 0.8, by = 0.1)
[1] 0.2 0.3 0.4 0.5 0.6 0.7 0.8

If I remember correctly the default increment for a:b is one unit.  Let's check a toy example:

> a <- 1; b <- 7
> a:b
[1] 1 2 3 4 5 6 7

If we do this with a <- 0.2 and b <- 0.8 the resulting vector would consist of just the value 0.2 hence, your code just detects such value.


问:
Issue with transform ldapsearch command to flask_ldap3_login settings
I have a problem with transform ldapsearch command to flask_ldap3_login settings.

To check connection to LDAP from Linux server I use this command:

```<code>ldapsearch -x -b "ou=intranet,dc=mydreamcorporation,dc=com" -H ldap://ids.mydream-corporation.com -D "myguid=myusername,ou=people,ou=intranet,dc=dreamcorporation,dc=com" -W "uid=myusername" cn uid
</code>```

Response from LDAP:

extended LDIF

LDAPv3

base <ou=intranet,dc=mydreamcorporation,dc=com> with scope subtree

filter: uid=myusername

requesting: cn uid

MYUSERNAME, people, intranet, mydreamcorporation.com

dn: myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com

cn: my_name

uid: MYUSERNAME

search result

search: 2

result: 0 Success

numResponses: 2

numEntries: 1

My flask_ldap3_login settings:

```<code>from flask import Flask, url_for
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager, login_user, UserMixin, current_user
from flask import render_template_string, redirect
from flask_ldap3_login.forms import LDAPLoginForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

my_login = "myusername"
my_password = "password"

# Hostname of your LDAP Server
app.config['LDAP_HOST'] = 'ldap://ids.mydream-corporation.com'

# Port number of your LDAP server
app.config['LDAP_PORT'] = 389

# Base DN of your directory
app.config['LDAP_BASE_DN'] = "dc=mydreamcorporation,dc=com"

# Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = "ou=intranet"

# Groups DN to be prepended to the Base DN
app.config['LDAP_GROUP_DN'] = 'ou=people'

# The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'dn'

# The Attribute you want users to authenticate to LDAP with.
app.config['LDAP_USER_LOGIN_ATTR'] = 'myguid'

# The Username to bind to LDAP with
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"

# The Password to bind to LDAP with
app.config['LDAP_BIND_USER_PASSWORD'] = my_password

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager

@app.route('/', methods=['POST','GET'])
def manual_login(my_login=my_login, my_password=my_password):
    result = app.ldap3_login_manager.authenticate(my_login, my_password)
    return str(result.status)
</code>```

Unfortunately I have as a script result:

AuthenticationResponseStatus.fail

I think the problem is in wrong configuration, but I cannot find where :(

I tried to add:

```<code>app.config['LDAP_USER_SEARCH_SCOPE'] = 'SUBTREE'
app.config['LDAP_ALWAYS_SEARCH_BIND'] = 1
</code>```

but it didn't help and I have a message:

invalid class in objectClass attribute: group

After Gabriel Luci comment I have change my settings to:

```<code>app.config['LDAP_BASE_DN'] = "ou=intranet"
app.config['LDAP_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"
#app.config['LDAP_GROUP_DN'] = 'ou=people'
app.config['LDAP_USER_RDN_ATTR'] = 'cn'
app.config['LDAP_USER_LOGIN_ATTR'] = 'uid'
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername"
</code>```

And now I have the same

AuthenticationResponseStatus.fail

And in console:

LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None

答:
I have an answer to the question. Problem was solved by adding:
app.config['LDAP_SEARCH_FOR_GROUPS'] = False

Final config:

```<code>app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

my_login = "myusername"
my_password = "password"

app.config['LDAP_HOST'] = 'ldaps://ids.mydream-corporation.com'
app.config['LDAP_PORT'] = 636
app.config['LDAP_BASE_DN'] = "dc=mydreamcorporation,dc=com"
app.config['LDAP_USER_DN'] = "ou=people,ou=intranet"
app.config['LDAP_USER_LOGIN_ATTR'] = 'myguid'
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"
app.config['LDAP_BIND_USER_PASSWORD'] = my_password
app.config['LDAP_USER_SEARCH_SCOPE'] = 'SUBTREE'
app.config['LDAP_SEARCH_FOR_GROUPS'] = False

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager

@app.route('/', methods=['POST','GET'])
def manual_login(my_login=my_login, my_password=my_password):
    result = app.ldap3_login_manager.authenticate(my_login, my_password)
    return str(result.status)
</code>```

Finally I have as a script result:

AuthenticationResponseStatus.success

Body:
I have a problem with transform ldapsearch command to flask_ldap3_login settings.

To check connection to LDAP from Linux server I use this command:

ldapsearch -x -b "ou=intranet,dc=mydreamcorporation,dc=com" -H ldap://ids.mydream-corporation.com -D "myguid=myusername,ou=people,ou=intranet,dc=dreamcorporation,dc=com" -W "uid=myusername" cn uid

Response from LDAP:

extended LDIF

LDAPv3

base <ou=intranet,dc=mydreamcorporation,dc=com> with scope subtree

filter: uid=myusername

requesting: cn uid

MYUSERNAME, people, intranet, mydreamcorporation.com

dn: myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com

cn: my_name

uid: MYUSERNAME

search result

search: 2

result: 0 Success

numResponses: 2

numEntries: 1

My flask_ldap3_login settings:

from flask import Flask, url_for
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager, login_user, UserMixin, current_user
from flask import render_template_string, redirect
from flask_ldap3_login.forms import LDAPLoginForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

my_login = "myusername"
my_password = "password"

# Hostname of your LDAP Server
app.config['LDAP_HOST'] = 'ldap://ids.mydream-corporation.com'

# Port number of your LDAP server
app.config['LDAP_PORT'] = 389

# Base DN of your directory
app.config['LDAP_BASE_DN'] = "dc=mydreamcorporation,dc=com"

# Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = "ou=intranet"

# Groups DN to be prepended to the Base DN
app.config['LDAP_GROUP_DN'] = 'ou=people'

# The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'dn'

# The Attribute you want users to authenticate to LDAP with.
app.config['LDAP_USER_LOGIN_ATTR'] = 'myguid'

# The Username to bind to LDAP with
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"

# The Password to bind to LDAP with
app.config['LDAP_BIND_USER_PASSWORD'] = my_password

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager

@app.route('/', methods=['POST','GET'])
def manual_login(my_login=my_login, my_password=my_password):
    result = app.ldap3_login_manager.authenticate(my_login, my_password)
    return str(result.status)

Unfortunately I have as a script result:

AuthenticationResponseStatus.fail

I think the problem is in wrong configuration, but I cannot find where :(

I tried to add:

app.config['LDAP_USER_SEARCH_SCOPE'] = 'SUBTREE'
app.config['LDAP_ALWAYS_SEARCH_BIND'] = 1

but it didn't help and I have a message:

invalid class in objectClass attribute: group

After Gabriel Luci comment I have change my settings to:

app.config['LDAP_BASE_DN'] = "ou=intranet"
app.config['LDAP_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"
#app.config['LDAP_GROUP_DN'] = 'ou=people'
app.config['LDAP_USER_RDN_ATTR'] = 'cn'
app.config['LDAP_USER_LOGIN_ATTR'] = 'uid'
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername"

And now I have the same

AuthenticationResponseStatus.fail

And in console:

LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None

Body:
I have an answer to the question. Problem was solved by adding:
app.config['LDAP_SEARCH_FOR_GROUPS'] = False

Final config:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

my_login = "myusername"
my_password = "password"

app.config['LDAP_HOST'] = 'ldaps://ids.mydream-corporation.com'
app.config['LDAP_PORT'] = 636
app.config['LDAP_BASE_DN'] = "dc=mydreamcorporation,dc=com"
app.config['LDAP_USER_DN'] = "ou=people,ou=intranet"
app.config['LDAP_USER_LOGIN_ATTR'] = 'myguid'
app.config['LDAP_BIND_USER_DN'] = "myguid=myusername,ou=people,ou=intranet,dc=mydreamcorporation,dc=com"
app.config['LDAP_BIND_USER_PASSWORD'] = my_password
app.config['LDAP_USER_SEARCH_SCOPE'] = 'SUBTREE'
app.config['LDAP_SEARCH_FOR_GROUPS'] = False

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager

@app.route('/', methods=['POST','GET'])
def manual_login(my_login=my_login, my_password=my_password):
    result = app.ldap3_login_manager.authenticate(my_login, my_password)
    return str(result.status)

Finally I have as a script result:

AuthenticationResponseStatus.success


问:
Sum similar keys in an array of objects
I have an array of objects like the following:

```<code>[
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]
</code>```

I need to add up all the values for objects with the same name. (Probably also other mathematical operations like calculate average.) For the example above the result would be:

```<code>[
    {
        'name': 'P1',
        'value': 300
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]
</code>```

答:
I see these complicated reduce with Array from and Map and Set - this is far simpler

const summed = arr.reduce((acc, cur, i) => {
  const item = i > 0 && acc.find(({name}) => name === cur.name)
  if (item) item.value += cur.value;
  else acc.push({ name: cur.name, value: cur.value }); // don't push cur here
  return acc;
}, [])
console.log(arr); // not modified
console.log(summed);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  const arr = [{
      'name': 'P1',
      'value': 150
    },
    {
      'name': 'P1',
      'value': 150
    },
    {
      'name': 'P2',
      'value': 200
    },
    {
      'name': 'P3',
      'value': 450
    }
  ]
</script></code>```

Title: Sum similar keys in an array of objects

Body:
I have an array of objects like the following:

[
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]

I need to add up all the values for objects with the same name. (Probably also other mathematical operations like calculate average.) For the example above the result would be:

[
    {
        'name': 'P1',
        'value': 300
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]

Body:
I see these complicated reduce with Array from and Map and Set - this is far simpler

const summed = arr.reduce((acc, cur, i) => {
  const item = i > 0 && acc.find(({name}) => name === cur.name)
  if (item) item.value += cur.value;
  else acc.push({ name: cur.name, value: cur.value }); // don't push cur here
  return acc;
}, [])
console.log(arr); // not modified
console.log(summed);

<script>
  const arr = [{
      'name': 'P1',
      'value': 150
    },
    {
      'name': 'P1',
      'value': 150
    },
    {
      'name': 'P2',
      'value': 200
    },
    {
      'name': 'P3',
      'value': 450
    }
  ]
</script>


问:
Value cannot be null. Parameter name: String
Please take a look at the following code. It's in handler.asxh.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    new RequestManagementFacade().PinRequest(Int32.Parse(context.Request.QueryString["requestId"]), (Boolean.Parse(context.Request.QueryString["isPinned"])));
}
```

<p>This is showing the following error:</p>

<pre class="lang-sh prettyprint-override"><code>Value cannot be null. Parameter name: String
</code>```

There is value being passed as I have checked the context request query string, however, the code breaks at this stage.

This handler will connect to the business logic layer.

答: experienced the error while using Int32.Parse(myString) to convert string to int and afterwards assign the value to an object's attribute. Using another method for converting(Convert.ToInt32(myString)) string to int worked for me.

Body:
Please take a look at the following code. It's in handler.asxh.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    new RequestManagementFacade().PinRequest(Int32.Parse(context.Request.QueryString["requestId"]), (Boolean.Parse(context.Request.QueryString["isPinned"])));
}

This is showing the following error:

Value cannot be null. Parameter name: String

There is value being passed as I have checked the context request query string, however, the code breaks at this stage.

This handler will connect to the business logic layer.


答: DataGrip does not convert any data received from database, so if you don't want to use built-in function, you should store data in table using the format you like from the beginning.</p>

Title: How to change the view of the geometry type column in the DataGrip?

Body:
English is not my first language, so please point out any mistakes.

I am using PostgreSQL with postgis installed.

My table DDL:

create table geo_teble
(
    latitude     numeric(12, 8),
    longitude    numeric(12, 8),
    geom         public.geometry
);

The geometry data in my table usually looks like raw data.

longitude
latitude
geom

127.72793149
34.91585546
01060000000200000001030000000100000005000000F98E01A8F9E75F40B6F82F508A7241400AFEEE1D15E95F400D3342544F704140F142F81C05ED5F4086EE0258817541405720CDB729EC5F405FCE129181774140F98E01A8F9E75F40B6F82F508A7241400103000000010000000600000065272DFF0AED5F40020C3E8F66744140A47C9CA128ED5F407E957D764677414072D3174DBFF05F40C10D3CEA4A7B4140C6187A10A9F25F404A3772A60375414057914A1BC3F25F409EA685118270414065272DFF0AED5F40020C3E8F66744140

If I use the command below, it looks like an execution result:

select longitude, latitude, st_astext(geom)
from geo_table;

longitude
latitude
st_astext

127.72793149
34.91585546
MULTIPOLYGON(((127.624612809679 34.8948459848629,127.641913874999 34.8774209330787,127.703437082713 34.9180097593608,127.690046263045 34.9336415616824,127.624612809679 34.8948459848629)),((127.703796190353 34.90937986879,127.705604937381 34.9318378556445,127.761676095264 34.9632237237197,127.791568869815 34.9141738946624,127.793158362217 34.8789693739502,127.703796190353 34.90937986879)))

But I want to see the converted data without executing the command. What should I do?


问:
Deep recursion in Scheme
I have a problem with deep recursion in scheme
The output should be

```<code>(1 2 3 (4 5))
  ~> ((1) (2) (3) ((4) (5)))
</code>```

But my output is (1 (2 (3 ((4 (5 ())) ())))).
It seems like the quote is at the wrong place
I got these

```<code>(define (DoublebubbleLst lst)
  (cond ((null? lst) lst)
        ((not (pair? lst))
         (append lst))
        (else(list
              (DoublebubbleLst (car lst))
              (DoublebubbleLst (cdr lst))))))
</code>```

And what's my problem

答:
This seems to work:

```<code>(define (double-bubble-list lst)
  (cond ((null? lst) lst)
        ((not (list? (car lst)))
         (cons (list (car lst))
               (double-bubble-list (cdr lst))))
        (else (cons (double-bubble-list (car lst))
                    (double-bubble-list (cdr lst))))))
</code>```

Example:

```<code>> (double-bubble-list '(1 2 3 (4 5)))
'((1) (2) (3) ((4) (5)))
</code>```

Title: Deep recursion in Scheme

Body:
I have a problem with deep recursion in scheme
The output should be

(1 2 3 (4 5))
  ~> ((1) (2) (3) ((4) (5)))

But my output is (1 (2 (3 ((4 (5 ())) ())))).
It seems like the quote is at the wrong place
I got these

(define (DoublebubbleLst lst)
  (cond ((null? lst) lst)
        ((not (pair? lst))
         (append lst))
        (else(list
              (DoublebubbleLst (car lst))
              (DoublebubbleLst (cdr lst))))))

And what's my problem

Body:
This seems to work:

(define (double-bubble-list lst)
  (cond ((null? lst) lst)
        ((not (list? (car lst)))
         (cons (list (car lst))
               (double-bubble-list (cdr lst))))
        (else (cons (double-bubble-list (car lst))
                    (double-bubble-list (cdr lst))))))

Example:

> (double-bubble-list '(1 2 3 (4 5)))
'((1) (2) (3) ((4) (5)))


问:
Get the first character of the first string in a list?
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

```<code>>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
</code>```

答: Try mylist[0][0]. This should return the first character.

Body:
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'


问:
TEXTJOIN cells unless a cell contain part of a string
I have several tables that represent rooms in our office, each table includes a column of few cells contain workers names and a device named like  the following "Device A", "device B" etc.

Table 1:

HR G1:G6

George

Ema

Benjamin

Johanna

Device A

Table 2:

Dev H1:H6

Josh

Jenna

Tom

Jessica

Device B

I want to summarize all their names exclude the device to a cell on a new table.

Table 3:

Room
NAME                   A1:B3

HR
George, Ema, Benjamin, Johanna

Dev
Josh, Jenna, Tom, Jessica

The issue is that I can change the devices order so the names on the table can change often.

I want to use TEXTJOIN (or other tool) to combine all cells unless the cell includes "Device" in it, without specify exactly which one.

I tried to use REGEXMATCH, VLOOKUP, SEARCH, COUNTIF but they all return a list, so its not working well inside TEXTJOIN.

I've tried to use FILTER too but wildcard doesn't work there so I must provide the full name of the device.

Please your advice,
Thanks in advance!

答:
You should be able to do something like

```<code>=textjoin(", ", 1, filter(G1:G6, not(regexmatch(G1:G6, "Device"))))
</code>```

or

```<code>=textjoin(", ", 1, filter(G1:G6, left(G1:G6, 6) <> "Device"))
</code>```

(Include the sheet name if you want the results to appear on a different tab).

Body:
You should be able to do something like

=textjoin(", ", 1, filter(G1:G6, not(regexmatch(G1:G6, "Device"))))

or

=textjoin(", ", 1, filter(G1:G6, left(G1:G6, 6) <> "Device"))

(Include the sheet name if you want the results to appear on a different tab).


问:
javascript reduce on properties of an array of objects acting weird
I have an array like this:

```<code>parts: [
      {
        name: 'Fundamentals of React',
        exercises: 10,
        id: 1
      },
      {
        name: 'Using props to pass data',
        exercises: 7,
        id: 2
      },
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      },
      {
        name: 'Redux',
        exercises: 11,
        id: 4
      }
    ]
</code>```

I would like to get the sum of the excercises. I'm trying to accomplish it thusly:

```<code>const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return prev.exercises + cur.exercises
  })

  return (
    <>
      <p>Number of exercises {total}</p>
    </>
  )
}
</code>```

But this results in NaN. The console shows why this result occurs, but not why the prev.excercises value is acting weird:

```<code>prev.excercises :  10
cur.excercises :  7
prev.excercises :  undefined
cur.excercises :  14
prev.excercises :  undefined
cur.excercises :  11
</code>```

I'm really new to js, so there is probably something really simple I'm doing wrong.. appreciate the help in advance!

答:
I also got it working like this, but I guess Ahmed Ali's answer is more to the nose!</p>
```<code>const Total = (props) => {

  const total = props.parts.map(part => part.exercises).
  reduce((prev, cur) => {
    console.log('prev : ', prev)
    console.log('cur : ', cur)
    return prev + cur
  })
</code>```

Body:
I have an array like this:

parts: [
      {
        name: 'Fundamentals of React',
        exercises: 10,
        id: 1
      },
      {
        name: 'Using props to pass data',
        exercises: 7,
        id: 2
      },
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      },
      {
        name: 'Redux',
        exercises: 11,
        id: 4
      }
    ]

I would like to get the sum of the excercises. I'm trying to accomplish it thusly:

const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return prev.exercises + cur.exercises
  })

  return (
    <>

Number of exercises {total}

    </>
  )
}

But this results in NaN. The console shows why this result occurs, but not why the prev.excercises value is acting weird:

prev.excercises :  10
cur.excercises :  7
prev.excercises :  undefined
cur.excercises :  14
prev.excercises :  undefined
cur.excercises :  11

I'm really new to js, so there is probably something really simple I'm doing wrong.. appreciate the help in advance!

Body:
I also got it working like this, but I guess Ahmed Ali's answer is more to the nose!

const Total = (props) => {

  const total = props.parts.map(part => part.exercises).
  reduce((prev, cur) => {
    console.log('prev : ', prev)
    console.log('cur : ', cur)
    return prev + cur
  })