问:
SeeMore Functionality for Xamarin Forms
I am developing a xamarin forms project. I need to a Label with in a listview which by default display max of 2 lines and then shows elipses(...) also I want to add a readmore button which enable the user to view the truncated text. Again the text need to be truncated when button is clicked. It is like "See more" & "See less" functionality. I have made it display 3 by using max lines property. Please anyone suggest me how to achieve this. I have added the screenshot for further reference.

This is my XAML For the label.

```<code><Label Text="{Binding Note, Mode=TwoWay}" Padding="0,0,0,0" MaxLines="3"
       LineBreakMode="TailTruncation" Style="{StaticResource TabContentLabelStyle}"
       IsVisible="{Binding IsEdit,Converter={StaticResource BoolConverter}}" />
</code>```

This is how it should look when Collapsed:

答:
Made a quick sample based on what @anand said

Create custom control called CustomLabel

CustomLabel.xaml

```<code><ContentView
    x:Class="BlankApp3.Controls.CustomLabel"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com"
    mc:Ignorable="d">

    <ContentView.Content>
        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Label x:Name="customLabel" />
            <Label
                x:Name="lblReadMore"
                FontSize="18"
                TextColor="#1a0fa9">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
                </Label.GestureRecognizers>
            </Label>
        </StackLayout>
    </ContentView.Content>
</ContentView>
</code>```

Code behind

```<code>using System;
using System.Diagnostics;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BlankApp3.Controls
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomLabel : ContentView
    {
        public CustomLabel()
        {
            InitializeComponent();
        }

        #region Bindable Property

        public static readonly BindableProperty TextProperty = BindableProperty.Create(
            propertyName: nameof(TextProperty),
            returnType: typeof(string),
            declaringType: typeof(CustomLabel),
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: TextPropertyChanged
            );

        public string Text
        {
            get { return (string)base.GetValue(TextProperty); }
            set { base.SetValue(TextProperty, value); }
        }

        private static void TextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (CustomLabel)bindable;
            if (newValue != null)
            {
                control.customLabel.Text = (string)newValue;
                var ss = control.customLabel.Text.Split().Length;
                if (control.customLabel.Text.Split().Length >= 30)
                {
                    control.ShortTextVisible = true;
                    control.ReadMoreLabel = true;
                }
            }
        }

        #endregion Bindable Property

        public bool ReadMoreLabel { get; set; }
        private bool _shortTextVisible;

        public bool ShortTextVisible
        {
            get => _shortTextVisible;
            set { _shortTextVisible = value; ShortTextPropertyChanged(); }
        }

        private void ShortTextPropertyChanged()
        {
            if (Text != null && Text.Split().Length >= 30)
            {
                if (ShortTextVisible)
                {
                    if (customLabel != null && !string.IsNullOrWhiteSpace(customLabel.Text) && customLabel.Text.Split().Length < 100)
                    {
                        Debug.WriteLine("");
                    }

                    customLabel.Text = string.Join(" ", Text.Split().Take(30));
                    lblReadMore.Text = "See more";
                    lblReadMore.IsVisible = true;
                }
                else
                {
                    customLabel.Text = Text;
                    lblReadMore.Text = "See less";
                }
            }
        }

        private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            ShortTextVisible = !ShortTextVisible;
        }
    }
}
</code>```

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="BlankApp3.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:BlankApp3.Controls"
    Title="{Binding Title}"
    BackgroundColor="#ffffff">

    <CollectionView ItemsSource="{Binding Monkeys}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>

                    <StackLayout Padding="10" Orientation="Horizontal">

                        <Image
                            HeightRequest="80"
                            Source="https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX13204546.jpg"
                            VerticalOptions="Start" />

                        <StackLayout HorizontalOptions="FillAndExpand">
                            <Frame
                                Margin="10,0,10,0"
                                BackgroundColor="#f9f9f9"
                                CornerRadius="10"
                                HasShadow="False">
                                <StackLayout>
                                    <Label FontAttributes="Bold" Text="Dr. Gracy David" />
                                    <local:CustomLabel Text="{Binding .}" />
                                </StackLayout>
                            </Frame>

                            <StackLayout Margin="10,0,10,0" Orientation="Horizontal">
                                <Label Text="12 April,2020" />
                                <Label Text="3.20pm" />
                            </StackLayout>
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage>
</code>```

MainPageViewModal.cs

```<code>using Prism.Navigation;
using System.Collections.ObjectModel;

namespace BlankApp3.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public ObservableCollection<string> Monkeys { get; set; }

        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Main Page";

            Monkeys = new ObservableCollection<string>();
        }

        public async override void OnNavigatedTo(INavigationParameters parameters)
        {
            Monkeys = new ObservableCollection<string>()
            {
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                 "Simple",
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            };
        }
    }
}
</code>```

Title: SeeMore Functionality for Xamarin Forms

Body:
I am developing a xamarin forms project. I need to a Label with in a listview which by default display max of 2 lines and then shows elipses(...) also I want to add a readmore button which enable the user to view the truncated text. Again the text need to be truncated when button is clicked. It is like "See more" & "See less" functionality. I have made it display 3 by using max lines property. Please anyone suggest me how to achieve this. I have added the screenshot for further reference.

This is my XAML For the label.

This is how it should look when Collapsed:

Body:
Made a quick sample based on what @anand said

Create custom control called CustomLabel

CustomLabel.xaml

<ContentView
    x:Class="BlankApp3.Controls.CustomLabel"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com"
    mc:Ignorable="d">

    <ContentView.Content>
        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Label x:Name="customLabel" />
            <Label
                x:Name="lblReadMore"
                FontSize="18"
                TextColor="#1a0fa9">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
                </Label.GestureRecognizers>
            </Label>
        </StackLayout>
    </ContentView.Content>
</ContentView>

Code behind

using System;
using System.Diagnostics;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BlankApp3.Controls
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomLabel : ContentView
    {
        public CustomLabel()
        {
            InitializeComponent();
        }

        #region Bindable Property

        public static readonly BindableProperty TextProperty = BindableProperty.Create(
            propertyName: nameof(TextProperty),
            returnType: typeof(string),
            declaringType: typeof(CustomLabel),
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: TextPropertyChanged
            );

        public string Text
        {
            get { return (string)base.GetValue(TextProperty); }
            set { base.SetValue(TextProperty, value); }
        }

        private static void TextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (CustomLabel)bindable;
            if (newValue != null)
            {
                control.customLabel.Text = (string)newValue;
                var ss = control.customLabel.Text.Split().Length;
                if (control.customLabel.Text.Split().Length >= 30)
                {
                    control.ShortTextVisible = true;
                    control.ReadMoreLabel = true;
                }
            }
        }

        #endregion Bindable Property

        public bool ReadMoreLabel { get; set; }
        private bool _shortTextVisible;

        public bool ShortTextVisible
        {
            get => _shortTextVisible;
            set { _shortTextVisible = value; ShortTextPropertyChanged(); }
        }

        private void ShortTextPropertyChanged()
        {
            if (Text != null && Text.Split().Length >= 30)
            {
                if (ShortTextVisible)
                {
                    if (customLabel != null && !string.IsNullOrWhiteSpace(customLabel.Text) && customLabel.Text.Split().Length < 100)
                    {
                        Debug.WriteLine("");
                    }

                    customLabel.Text = string.Join(" ", Text.Split().Take(30));
                    lblReadMore.Text = "See more";
                    lblReadMore.IsVisible = true;
                }
                else
                {
                    customLabel.Text = Text;
                    lblReadMore.Text = "See less";
                }
            }
        }

        private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            ShortTextVisible = !ShortTextVisible;
        }
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="BlankApp3.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:BlankApp3.Controls"
    Title="{Binding Title}"
    BackgroundColor="#ffffff">

    <CollectionView ItemsSource="{Binding Monkeys}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>

                    <StackLayout Padding="10" Orientation="Horizontal">

                        <Image
                            HeightRequest="80"
                            Source="https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX13204546.jpg"
                            VerticalOptions="Start" />

                        <StackLayout HorizontalOptions="FillAndExpand">
                            <Frame
                                Margin="10,0,10,0"
                                BackgroundColor="#f9f9f9"
                                CornerRadius="10"
                                HasShadow="False">
                                <StackLayout>
                                    <Label FontAttributes="Bold" Text="Dr. Gracy David" />
                                    <local:CustomLabel Text="{Binding .}" />
                                </StackLayout>
                            </Frame>

                            <StackLayout Margin="10,0,10,0" Orientation="Horizontal">
                                <Label Text="12 April,2020" />
                                <Label Text="3.20pm" />
                            </StackLayout>
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage>

MainPageViewModal.cs

using Prism.Navigation;
using System.Collections.ObjectModel;

namespace BlankApp3.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public ObservableCollection<string> Monkeys { get; set; }

        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Main Page";

            Monkeys = new ObservableCollection<string>();
        }

        public async override void OnNavigatedTo(INavigationParameters parameters)
        {
            Monkeys = new ObservableCollection<string>()
            {
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                 "Simple",
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            };
        }
    }
}


来源: stackexchange

问:
Select All checkboxes using jQuery
I have the following html code:

```<code>    <input type="checkbox" id="ckbCheckAll" />
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>
</code>```

When user checks ckbCheckAll all checkboxes must be checked. Also I have following jquery code:

```<code>    $(document).ready(function () {
        $("#ckbCheckAll").click(function () {
            $(".checkBoxClass").attr('checked', this.checked);
        });
    });
</code>```

When I see my page in the browser I get the following result:
In the first click on ckbCheckAll all checkboxes were checked (which is correct). In the second click on ckbCheckAll all checkboxes were unchecked (which is correct). But in 3rd attempt nothing happened! also in 4th attempt nothing happened and so on.

Where is the problem?

答:
I know its too late, but I'm posting this for the upcoming developers.

For select all checkbox we need to check three conditions,
1. on click select all checkbox every checkbox should get selected
2. if all selected then on click select all checkbox, every checkbox should get deselected
3. if we deselect or select any of the checkbox the select all checkbox also should change.

with these three things we'll get a good result.for this you can approach this link https://qawall.in/2020/05/30/select-all-or-deselect-all-checkbox-using-jquery/
I got my solution from here, they have provided solution with examples.

```<code><table>
<tr>
    <th><input type="checkbox" id="select_all"/> Select all</th>
</tr>
<tr>
    <td><input type="checkbox" class="check" value="1"/> Check 1</td>
    <td><input type="checkbox" class="check" value="2"/> Check 2</td>
    <td><input type="checkbox" class="check" value="3"/> Check 3</td>
    <td><input type="checkbox" class="check" value="4"/> Check 4</td>
    <td><input type="checkbox" class="check" value="5"/> Check 5</td>
</tr>
</code>```

```<code><script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
    if(this.checked){
        $('.check').each(function(){
            this.checked = true;
        });
    }else{
         $('.check').each(function(){
            this.checked = false;
        });
    }
});

$('.check').on('click',function(){
    if($('.check:checked').length == $('.check').length){
        $('#select_all').prop('checked',true);
    }else{
        $('#select_all').prop('checked',false);
    }
});
</code>```

});

hope this will help anyone ...:)

ContentLicense: CC BY-SA 3.0

Title: Select All checkboxes using jQuery

Body:
I have the following html code:

    <input type="checkbox" id="ckbCheckAll" />

        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />

        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />

        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />

        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />

        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />

When user checks ckbCheckAll all checkboxes must be checked. Also I have following jquery code:

    $(document).ready(function () {
        $("#ckbCheckAll").click(function () {
            $(".checkBoxClass").attr('checked', this.checked);
        });
    });

When I see my page in the browser I get the following result:
In the first click on ckbCheckAll all checkboxes were checked (which is correct). In the second click on ckbCheckAll all checkboxes were unchecked (which is correct). But in 3rd attempt nothing happened! also in 4th attempt nothing happened and so on.

Where is the problem?

Body:
I know its too late, but I'm posting this for the upcoming developers.

For select all checkbox we need to check three conditions,
1. on click select all checkbox every checkbox should get selected
2. if all selected then on click select all checkbox, every checkbox should get deselected
3. if we deselect or select any of the checkbox the select all checkbox also should change.

with these three things we'll get a good result.for this you can approach this link https://qawall.in/2020/05/30/select-all-or-deselect-all-checkbox-using-jquery/
I got my solution from here, they have provided solution with examples.

<table>
<tr>
    <th><input type="checkbox" id="select_all"/> Select all</th>
</tr>
<tr>
    <td><input type="checkbox" class="check" value="1"/> Check 1</td>
    <td><input type="checkbox" class="check" value="2"/> Check 2</td>
    <td><input type="checkbox" class="check" value="3"/> Check 3</td>
    <td><input type="checkbox" class="check" value="4"/> Check 4</td>
    <td><input type="checkbox" class="check" value="5"/> Check 5</td>
</tr>

<script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
    if(this.checked){
        $('.check').each(function(){
            this.checked = true;
        });
    }else{
         $('.check').each(function(){
            this.checked = false;
        });
    }
});

$('.check').on('click',function(){
    if($('.check:checked').length == $('.check').length){
        $('#select_all').prop('checked',true);
    }else{
        $('#select_all').prop('checked',false);
    }
});

});

hope this will help anyone ...:)

ContentLicense: CC BY-SA 4.0


问:
How does Grakn compute rules when running a query for a transitive relation?
I'm working in memSQL on a project to identify certain batter pitcher relationships in the MLB; where I look at what batters had the most success against various pitchers and when. With the goal of creating a heat map of teams and lineups of a specific year(s)(collection of batters) against various groups of pitchers.

I ran into a problem trying to query for teams with a positive net score against pitchers. When looking for all Batter of a given team.

I came across Grakn and this blog post: https://blog.grakn.ai/comparing-graql-to-sql-part-2-2-745f79e9528d

Seems that I could utilise rules to then query for something like this.

Taking a stab at the rule - I want to make team performance against a pitcher based on a collection of batter performance of that same pitcher.

I wrote this query, which would just query for at-bat performance where batter is in a plays-for with a given team. However the query doesn't give me the result I am expecting?

```<code>when {
(batting: $b, pitching: $p) isa at-bat;
(playing: $b, plays-for: $t) isa team;
}, then {
(plays-for: $c, pitching: $d) isa at-bat;
};
</code>```

Also does anyone knows when these rules are computed and what is the performance overhead?

答:
Just to check quickly, are you defining the rule in your schema? Rules need to be inserted into Grakn using a define statement, since they are treated like schema elements. If you are trying to run it in-line in the query I would have thought you would get an error, but maybe that's not what you are doing and I am misunderstanding.

To answer the other question, rules are computed at query time, we detect which rules might change the outcome of a query and effectively make it a part of the query traversal, so in theory it works like a normal transitive search over a graph. In practice it's a bit different.

Body:
I'm working in memSQL on a project to identify certain batter pitcher relationships in the MLB; where I look at what batters had the most success against various pitchers and when. With the goal of creating a heat map of teams and lineups of a specific year(s)(collection of batters) against various groups of pitchers.

I ran into a problem trying to query for teams with a positive net score against pitchers. When looking for all Batter of a given team.

I came across Grakn and this blog post: https://blog.grakn.ai/comparing-graql-to-sql-part-2-2-745f79e9528d

Seems that I could utilise rules to then query for something like this.

Taking a stab at the rule - I want to make team performance against a pitcher based on a collection of batter performance of that same pitcher.

I wrote this query, which would just query for at-bat performance where batter is in a plays-for with a given team. However the query doesn't give me the result I am expecting?

when {
(batting: $b, pitching: $p) isa at-bat;
(playing: $b, plays-for: $t) isa team;
}, then {
(plays-for: $c, pitching: $d) isa at-bat;
};

Also does anyone knows when these rules are computed and what is the performance overhead?


问:
Problems with Rendering Component in React + Typescript
I'm trying to render certain content onto my screen but currently it's not showing up. I know the function is entering the if conditional since I tested it with console logging.

Here is where I write the conditional to render a certain content.

```<code>renderContent = (): Content => {
  this.props.contents.forEach((content:SomeType) => {
    if (content.booleanCondition){
      return <ImportantComponent contentData = {this.usefulFunction()}/>
    }
  }
}
</code>```

And here is where I want to render everything.

```<code>renderEverything = () => {
  return (
    {this.renderContent()}
  );
};
</code>```

Alternatively, is there a way I can directly write the conditional in the renderEverything so I don't have to call the function renderContent?

答:
If you want to render an ImportantComponent for each content element that satisfies the booleanCondition:

```<code>renderEverything = () => {
  return this.props.contents.map(
      content => content.booleanCondition && <ImportantComponent key={content} contentData = {this.usefulFunction()}/>
  )
}
</code>```

If you want to render only one ImportantComponent if any content element satisfies the booleanCondition:

```<code>renderEverything = () => {
  const contentToBeShown = this.props.contents.find(content => content.booleanCondition)
  if(contentToBeShown)
     return <ImportantComponent contentData = {this.usefulFunction()}/>
}
</code>```

Body:
I'm trying to render certain content onto my screen but currently it's not showing up. I know the function is entering the if conditional since I tested it with console logging.

Here is where I write the conditional to render a certain content.

renderContent = (): Content => {
  this.props.contents.forEach((content:SomeType) => {
    if (content.booleanCondition){
      return <ImportantComponent contentData = {this.usefulFunction()}/>
    }
  }
}

And here is where I want to render everything.

renderEverything = () => {
  return (
    {this.renderContent()}
  );
};

Alternatively, is there a way I can directly write the conditional in the renderEverything so I don't have to call the function renderContent?

Body:
If you want to render an ImportantComponent for each content element that satisfies the booleanCondition:

renderEverything = () => {
  return this.props.contents.map(
      content => content.booleanCondition && <ImportantComponent key={content} contentData = {this.usefulFunction()}/>
  )
}

If you want to render only one ImportantComponent if any content element satisfies the booleanCondition:

renderEverything = () => {
  const contentToBeShown = this.props.contents.find(content => content.booleanCondition)
  if(contentToBeShown)
     return <ImportantComponent contentData = {this.usefulFunction()}/>
}


问:
Javascript fetch doesn't return despite correct URL
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

```<code>this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}
</code>```

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

答:
Well I do get a response when a try with a mock url:
http://jsfiddle.net/0zavw15j/

getData('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
async function getData(url = '') {
const response = await fetch(url, {
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    cache: 'no-cache',
    headers: {
        'Content-Type': 'application/json'
    },
    redirect: 'follow',
    referrerPolicy: 'no-referrer'
});
   let commits = await response.json(); // read response body and parse as JSON

alert(commits);// <---- this is hitting
}```

Body:
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.


问:
rxjs `delay` makes Protractor E2E time out
When I ng e2e my app, I receive this error:

Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds.

Below is the app.component.ts. Notice how it publishes 'app' 15 seconds after you subscribe to it.

I realize that Protractor waits until there are no pending asynchronous tasks in your Angular application. Please keep reading.

```<code>import { Component } from '@angular/core';
import * as Rxjs from 'rxjs';
import * as Operators from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: Rxjs.Observable<string>;

  constructor() {
    this.title = Rxjs.of('app').pipe(
      Operators.delay(15000)
    );
  }
}
</code>```

Here's the corresponding change in app.component.html:

```<code>Welcome to {{ title | async }}!
</code>```

Everything else is bone stock (these are the only changes I made after ng new).

This of course is a silly example. My real-life code does something useful. I need to be able to have Observables which do not publish anything for very long periods of time (months, in my case).

Is there a way to use rxjs's delay operator in my app such that my end-to-end tests don't time out?

Or is there something I can do to signal to Protractor that it need not wait on a particular Observable?

Things I have tried:

browser.waitForAngularEnabled(false)

This does indeed cause Protractor to stop waiting, but is not a good solution because this is an Angular app and it makes everything harder.

ngZone.runOutsideAngular(() => {...})

This doesn't help because the long-running operation is happening through a view binding (the {{ title | async }}). That's not a place where I can stick a call to ngZone.runOutsideAngular.

答:
I had a similar issue with the rxjs timer, my protractor tests throw "ScriptTimeoutError: script timeout" exceptions all the time. The solution that worked for me was that I used the native selenium webdriver API on the pages with the timer. For example:

Instead of:

```<code>await element(by.id('question-12' )).click();
</code>```

I used the selenium webdriver:

```<code>import {By} from "selenium-webdriver";
//...
await browser.driver.findElement(By.id('question-12' )).click();
</code>```

Body:
When I ng e2e my app, I receive this error:

Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds.

Below is the app.component.ts. Notice how it publishes 'app' 15 seconds after you subscribe to it.

I realize that Protractor waits until there are no pending asynchronous tasks in your Angular application. Please keep reading.

import { Component } from '@angular/core';
import * as Rxjs from 'rxjs';
import * as Operators from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: Rxjs.Observable<string>;

  constructor() {
    this.title = Rxjs.of('app').pipe(
      Operators.delay(15000)
    );
  }
}

Here's the corresponding change in app.component.html:

Welcome to {{ title | async }}!

Everything else is bone stock (these are the only changes I made after ng new).

This of course is a silly example. My real-life code does something useful. I need to be able to have Observables which do not publish anything for very long periods of time (months, in my case).

Is there a way to use rxjs's delay operator in my app such that my end-to-end tests don't time out?

Or is there something I can do to signal to Protractor that it need not wait on a particular Observable?

Things I have tried:

browser.waitForAngularEnabled(false)

This does indeed cause Protractor to stop waiting, but is not a good solution because this is an Angular app and it makes everything harder.

ngZone.runOutsideAngular(() => {...})

This doesn't help because the long-running operation is happening through a view binding (the {{ title | async }}). That's not a place where I can stick a call to ngZone.runOutsideAngular.

Body:
I had a similar issue with the rxjs timer, my protractor tests throw "ScriptTimeoutError: script timeout" exceptions all the time. The solution that worked for me was that I used the native selenium webdriver API on the pages with the timer. For example:

Instead of:

await element(by.id('question-12' )).click();

I used the selenium webdriver:

import {By} from "selenium-webdriver";
//...
await browser.driver.findElement(By.id('question-12' )).click();


问:
Remove Pan control in Google Maps API V3
Is there any way to remove the circular panning navigation control but keep the zoom control in the Google Maps V3 API?  I've tried forcing it offscreen with jQuery but every time the map is updated it comes back.  Any ideas?  Thanks!</p>

答:
You may also have a look in here, you can remove/add specific controls when you declare your map:

```<code>var latlng = new google.maps.LatLng(40.44062, -79.99588);
var options = {
    zoom: 14,
    center: latlng,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
</code>```

Taking Control of the Google Maps API V3 Controls

ContentLicense: CC BY-SA 2.5

Body:
You may also have a look in here, you can remove/add specific controls when you declare your map:

var latlng = new google.maps.LatLng(40.44062, -79.99588);
var options = {
    zoom: 14,
    center: latlng,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

Taking Control of the Google Maps API V3 Controls


问:
Problem connecting MariaDB using PyMysql in Python
I have a Flask Python API that connects with a MariaDB database in a Docker container and I'm connecting to the database with PyMysql.

The problem is that my server or application closes the connection after 10 minutes.
I've already tried to increase the timeout time in the MariaDB configuration file and in PyMySQL, but to no avail. The errors are as follows:

Python error:

```<code>"OperationalError: (2006, "MySQL server has gone away
(ConnectionResetError(104, 'Connection reset by peer'))")"
</code>```

Database error:

```<code>"[Warning] Aborted connection 9 to db: 'db' user: 'user' host: 'ip'
(Got timeout reading communication packets)"
</code>```

Would anyone know how to solve the problem?

I give below my MariaDB configuration file and my Python code.

Thank you in advance.

PS: I've already tried to use another Python package to connect to MariaDB, that is through the Flask SQLAlchemy, but the same behavior happens with the database connection, unfortunately.
For that reason, I believe that the problem is not the Python code, but maybe the Docker image (maybe).

my.cnf

```<code># 7 days = 604800s / 8 hours = 28800s
wait_timeout = 604800
interactive_timeout = 28800
</code>```

Python code:

```<code>from pymysql import connect
from pymysql.cursors import DictCursor

class MySQLConnection:

    def __init__(self, host, port, user, password, schema):
        try:
            # Connect to the database
            self.connection = connect(host=host, port=port,
                                      user=user, password=password,
                                      db=schema, cursorclass=DictCursor,
                                      connect_timeout=50)

            # create a cursor object
            self.cursor = self.connection.cursor()
            print("DB connection was successful!")
        except Exception as error:
            print("DB connection was failed! \nError: ", error)
            exit(1)
</code>```

答:
https://docs.sqlalchemy.org/en/13/faq/connections.html#mysql-server-has-gone-away

Maybe you need pool_recycle, pool_pre_ping  :)

Body:
I have a Flask Python API that connects with a MariaDB database in a Docker container and I'm connecting to the database with PyMysql.

The problem is that my server or application closes the connection after 10 minutes.
I've already tried to increase the timeout time in the MariaDB configuration file and in PyMySQL, but to no avail. The errors are as follows:

Python error:

"OperationalError: (2006, "MySQL server has gone away
(ConnectionResetError(104, 'Connection reset by peer'))")"

Database error:

"[Warning] Aborted connection 9 to db: 'db' user: 'user' host: 'ip'
(Got timeout reading communication packets)"

Would anyone know how to solve the problem?

I give below my MariaDB configuration file and my Python code.

Thank you in advance.

PS: I've already tried to use another Python package to connect to MariaDB, that is through the Flask SQLAlchemy, but the same behavior happens with the database connection, unfortunately.
For that reason, I believe that the problem is not the Python code, but maybe the Docker image (maybe).

my.cnf

# 7 days = 604800s / 8 hours = 28800s
wait_timeout = 604800
interactive_timeout = 28800

Python code:

from pymysql import connect
from pymysql.cursors import DictCursor

class MySQLConnection:

    def __init__(self, host, port, user, password, schema):
        try:
            # Connect to the database
            self.connection = connect(host=host, port=port,
                                      user=user, password=password,
                                      db=schema, cursorclass=DictCursor,
                                      connect_timeout=50)

            # create a cursor object
            self.cursor = self.connection.cursor()
            print("DB connection was successful!")
        except Exception as error:
            print("DB connection was failed! \nError: ", error)
            exit(1)


问:
Writing Spark-SQL queries involving Complex types
I am new to Spark-SQL and trying to come to terms with it. We use Spark-SQL primarily for data transformations/manipulations for ETL. Recently, I have stumbled upon few SparkSQL functions for manipulating Spark Complex Types (array, map, struct etc). I came across certain functions such as array(), array_zip(), struct(), map_concat(), map_from_arrays() etc. I searched online but unfortunately, I could not get enough examples/explanations involving them for me to have a clear understanding.

Can anyone please provide some examples of its applications so that I can have a better understanding for me to be able to apply them in our project tasks.

Note: I only have access to Spark-SQL but Not PySpark-SQL.

Thanks

答:
Please go through below explination,

array

array(expr, ...) - Returns an array with the given elements.

Examples:

SELECT array(1, 2, 3);

  [1,2,3]

arrays_zip

arrays_zip(a1, a2, ...) - Returns a merged array of structs in which the N-th struct contains all N-th values of input arrays.

Examples:

SELECT arrays_zip(array(1, 2, 3), array(2, 3, 4));

   [{"0":1,"1":2},{"0":2,"1":3},{"0":3,"1":4}]

  SELECT arrays_zip(array(1, 2), array(2, 3), array(3, 4));

   [{"0":1,"1":2,"2":3},{"0":2,"1":3,"2":4}]

struct

struct(col1, col2, col3, ...) - Creates a struct with the given field values.

map

map(key0, value0, key1, value1, ...) - Creates a map with the given key/value pairs.

Examples:

SELECT map(1.0, '2', 3.0, '4');

   {1.0:"2",3.0:"4"}

map_concat

map_concat(map, ...) - Returns the union of all the given maps

Examples:

SELECT map_concat(map(1, 'a', 2, 'b'), map(2, 'c', 3, 'd'));

   {1:"a",2:"c",3:"d"}

map_from_arrays

map_from_arrays(keys, values) - Creates a map with a pair of the given key/value arrays. All elements in keys should not be null

Examples:

SELECT map_from_arrays(array(1.0, 3.0), array('2', '4'));

   {1.0:"2",3.0:"4"}

For more built in Spark functions, please go through below link,

https://spark.apache.org/docs/latest/api/sql/


问:
Writing csv.open as a function in Python
I'm almost a complete newbie in Python, so my question is very basic and probably naive.

I'm trying to include a csv.reader function into a custom function, because I think I might need to read several types of csv-like texts with various delimiters and quote chars and would like to quickly specify these parameters.

Here's the code I'm trying to do it with.

```<code>import csv

def openFile(inputPath, newline='', delimiter=',', quotechar='"'):
    with open(inputPath, newline='') as csvfile:
        openedFile = csv.reader(csvfile, delimiter, quotechar)
    return openedFile

inputPath = "unit_structure.csv"
ff = openFile(inputPath, delimiter=';')
print (ff)
</code>```

I get the following errors

on the line "openedFile = csv.reader(csvfile, delimiter, quotechar)" an error stating "expected at most 2 arguments, got 3". I've got this line of code from here https://docs.python.org/3/library/csv.html and it had 3 arguments there. I don't understand why it began giving an error after I've turned it into the function.

on the line "with open(inputPath, newline) as csvfile:" an error stating "Must have exactly one of create/read/write/append mode and at most one plus". This one I don't understand at all.

So I have three general questions.

First and foremost. Am I trying to do a correct thing, in general? I'm not sure that coding the function this way is efficient. "csv.reader" as already a function. Maybe I should just use "with open..." every time?

I don't understand why I get these errors. Maybe my understanding of the code structure is wrong? I think that line "with open" is a command to open a file at a specified address, "openedFile = csv.reader(...)" specifies it as a csv and then "return openedFile" returns a comma-delimited text itself. I suspect I might be wrong in this interpretation and this's why I don't understand where those error messages come from.

If my general understanding is correct, maybe someone could explain what am I doing wrong code-wise?

答:
Your first problem (errors from csv.reader()) are because you need to use named parameters (not positional) for delimiter and quotechar.

The main problem is that you cannot return a file object.  Python closes the file object for you before returning.  (Thanks, Python!)

But I discovered that you can yield an open file object.  (See the accepted answer to this question).

One more potential small problem I saw is that you are not passing your newline parameter to the open() - you are hard coding that to ''.

Here is a fixed up and tested version of your program:

import csv

def openFile(inputPath, newline='', delimiter=',', quotechar='"'):
    with open(inputPath, newline=newline) as csvfile:
        openedFile = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar)
        yield openedFile

inputPath = "unit_structure.csv"
ff = openFile(inputPath, delimiter=';')

print(ff)

for g in ff:
    [ print(';'.join(r)) for r in g ]
```

<p>With an input file <code>unit_structure.csv</code> containing this:</p>

```aaa;bbb;ccc
1;2;3
4;5;6
```

<p>the program prints this:</p>

```<generator object openFile at 0x7f89771f3e60>
aaa;bbb;ccc
1;2;3
4;5;6
```

Body:
I'm almost a complete newbie in Python, so my question is very basic and probably naive.

I'm trying to include a csv.reader function into a custom function, because I think I might need to read several types of csv-like texts with various delimiters and quote chars and would like to quickly specify these parameters.

Here's the code I'm trying to do it with.

import csv

def openFile(inputPath, newline='', delimiter=',', quotechar='"'):
    with open(inputPath, newline='') as csvfile:
        openedFile = csv.reader(csvfile, delimiter, quotechar)
    return openedFile

inputPath = "unit_structure.csv"
ff = openFile(inputPath, delimiter=';')
print (ff)

I get the following errors

on the line "openedFile = csv.reader(csvfile, delimiter, quotechar)" an error stating "expected at most 2 arguments, got 3". I've got this line of code from here https://docs.python.org/3/library/csv.html and it had 3 arguments there. I don't understand why it began giving an error after I've turned it into the function.

on the line "with open(inputPath, newline) as csvfile:" an error stating "Must have exactly one of create/read/write/append mode and at most one plus". This one I don't understand at all.

So I have three general questions.

First and foremost. Am I trying to do a correct thing, in general? I'm not sure that coding the function this way is efficient. "csv.reader" as already a function. Maybe I should just use "with open..." every time?

I don't understand why I get these errors. Maybe my understanding of the code structure is wrong? I think that line "with open" is a command to open a file at a specified address, "openedFile = csv.reader(...)" specifies it as a csv and then "return openedFile" returns a comma-delimited text itself. I suspect I might be wrong in this interpretation and this's why I don't understand where those error messages come from.

If my general understanding is correct, maybe someone could explain what am I doing wrong code-wise?

Body:
Your first problem (errors from csv.reader()) are because you need to use named parameters (not positional) for delimiter and quotechar.

The main problem is that you cannot return a file object.  Python closes the file object for you before returning.  (Thanks, Python!)

But I discovered that you can yield an open file object.  (See the accepted answer to this question).

One more potential small problem I saw is that you are not passing your newline parameter to the open() - you are hard coding that to ''.

Here is a fixed up and tested version of your program:

import csv

def openFile(inputPath, newline='', delimiter=',', quotechar='"'):
    with open(inputPath, newline=newline) as csvfile:
        openedFile = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar)
        yield openedFile

inputPath = "unit_structure.csv"
ff = openFile(inputPath, delimiter=';')

print(ff)

for g in ff:
    [ print(';'.join(r)) for r in g ]

With an input file unit_structure.csv containing this:

aaa;bbb;ccc
1;2;3
4;5;6

the program prints this:

<generator object openFile at 0x7f89771f3e60>
aaa;bbb;ccc
1;2;3
4;5;6


问:
ggplot2: How to assign different alpha-values for different fills in geom_ribbon()?
Question: is it possible to assign different alpha-values to different fill's in a geom_ribbon()?

I have the following reproducible example of a cumulative incidence function

I have

```<code>> table(res$CIF)

CIF0 1; treatment=Control     CIF0 1; treatment=SSA    CIF0 1; treatment=SSTR
                       35                        61                        25
</code>```

I would like complete opacity for res$CIF0 1; treatment=Control, ie. alpha=0, whereas the remaining two groups have alpha=0.2.

How can this be done?

```<code>ggplot(res, aes(time, P)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = CIF), alpha=0.2) +
  geom_line(aes(color = CIF)) +
  scale_x_continuous(breaks = seq(0,100,10)) +
  coord_cartesian(xlim=c(0,100))
</code>```

Data sample

```<code>res <- structure(list(CIF = c("CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control"), P = c(0.0116279069767442,
0.0348837209302326, 0.0813953488372093, 0.209302325581395, 0.267441860465116,
0.27906976744186, 0.351162790697674, 0.351162790697674, 0.363405002193945,
0.363405002193945, 0.363405002193945, 0.425891290039491, 0.438998169929045,
0.452105049818598, 0.452105049818598, 0.452105049818598, 0.452105049818598,
0.467711841066396, 0.467711841066396, 0.483896661619669, 0.501488857873226,
0.501488857873226, 0.501488857873226, 0.501488857873226, 0.533914431204164,
0.008, 0.032, 0.0402735042735043, 0.0485470085470086, 0.0568205128205128,
0.0650940170940171, 0.131282051282051, 0.139555555555556, 0.139555555555556,
0.156102564102564, 0.164376068376068, 0.172649572649573, 0.214017094017094,
0.222290598290598, 0.238837606837607, 0.255384615384615, 0.26365811965812,
0.280205128205128, 0.288577126577126, 0.296949124949125, 0.305321123321123,
0.313905071018995, 0.322489018716867, 0.331072966414738, 0.33965691411261,
0.356824809508354, 0.365527978702029, 0.365527978702029, 0.374231147895705,
0.383194113184714, 0.392157078473723, 0.401120043762732, 0.410225278342043,
0.419330512921354, 0.428744399520302, 0.438158286119251, 0.438158286119251,
0.447572172718199, 0.466399945916096, 0.475813832515045, 0.485412305125737,
0.504609250347123, 0.514625047853932, 0.554688237881171, 0.564704035387981,
0.574976648215478, 0.585249261042975, 0.595807224226791, 0.606365187410608,
0.619660400308747, 0.632955613206886, 0.646804793309115, 0.66356959027497,
0.66356959027497, 0.681320551768229, 0.71935832639664, 0.742180991173687,
0.742180991173687, 0.771524417315605, 0.800867843457522, 0.800867843457522,
0.025, 0.025, 0.025, 0.025, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15,
0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3, 0.325, 0.35, 0.375,
0.4, 0.425, 0.45, 0.478333333333333, 0.506666666666667, 0.535,
0.565909090909091, 0.596818181818182, 0.631590909090909, 0.666363636363636,
0.701136363636364, 0.735909090909091, 0.770681818181818, 0.805454545454545,
0.840227272727273), time = c(0.1, 1, 2, 3, 4, 5, 6, 7.7, 8, 8.9,
9.7, 12, 13, 13.8, 15.6, 16, 18, 21, 21.8, 22, 26.2, 32, 47.2,
57, 75.9, 0.72, 1, 1.02, 1.08, 1.48, 1.87, 2, 2.43, 2.66, 2.76,
2.82, 2.83, 3, 3.06, 3.08, 3.57, 3.88, 4, 4.11, 4.23, 4.4, 5.06,
5.07, 5.29, 5.49, 6, 6.37, 6.41, 6.9, 7.48, 7.79, 8, 8.03, 9,
9.13, 9.2, 9.25, 10, 10.8, 11, 11.04, 12, 13, 13.47, 14.2, 15.05,
16.1, 18, 19, 21.1, 21.42, 23.1, 26.91, 29.84, 30.85, 36, 37,
50.4, 55, 60, 227.26, 0.23, 0.26, 0.49, 0.53, 0.69, 3.15, 3.25,
4.5, 5.12, 5.78, 6.67, 7.65, 7.79, 7.85, 9, 9.99, 11.37, 12.68,
13.11, 15.05, 15.83, 16.89, 18.17, 22.7, 23.59, 29.6, 32.65,
35.81, 43, 43.79, 45.37, 46.45, 46.65, 69.02, 105.16), lower = c(0.00164617019552282,
0.0113856737746599, 0.0396576469212214, 0.137397969022517, 0.186547499227902,
0.196621316727872, 0.260256711254436, 0.260256711254436, 0.271275320611526,
0.271275320611526, 0.271275320611526, 0.328365028488864, 0.340443606650536,
0.35260199321003, 0.35260199321003, 0.35260199321003, 0.35260199321003,
0.366602928781548, 0.366602928781548, 0.381138644331497, 0.396763300880135,
0.396763300880135, 0.396763300880135, 0.396763300880135, 0.419758773874353,
0.00113079397933524, 0.0121318162766967, 0.0169602104591103,
0.0221020257192824, 0.0274924721924664, 0.0330871802437624, 0.0825552954975503,
0.0891475380978586, 0.0891475380978586, 0.10252950910509, 0.109310958190052,
0.116148022092879, 0.151072486742553, 0.158189875311549, 0.17254320156191,
0.187045456692541, 0.194349432892335, 0.209057919001854, 0.216533612164684,
0.224041664416515, 0.231581290225624, 0.239310242224555, 0.247071853759351,
0.254865425506176, 0.262690312701882, 0.278431702879287, 0.286438278832329,
0.286438278832329, 0.294475403714247, 0.302741263754617, 0.311039845699379,
0.319370690508033, 0.327842676656013, 0.336347856846665, 0.345122677072548,
0.353933917141138, 0.353933917141138, 0.362781191618168, 0.380582536935198,
0.389536065805856, 0.398668454798478, 0.417044839259437, 0.426613603797864,
0.465317914150164, 0.475101203906211, 0.485129775477843, 0.495205813090998,
0.505553356441026, 0.515954049816092, 0.528422874133768, 0.541020866739871,
0.55413162171834, 0.569264211367809, 0.569264211367809, 0.585292041073961,
0.62005426996364, 0.640223402829866, 0.640223402829866, 0.664192334088305,
0.690689472196916, 0.690689472196916, 0.00355981698627006, 0.00355981698627006,
0.00355981698627006, 0.00355981698627006, 0.00355981698627006,
0.0127444761396915, 0.0248237564000704, 0.0387548083597935, 0.0540289278928447,
0.0703518337133965, 0.0703518337133965, 0.0875349177801499, 0.105448804967606,
0.124000413393049, 0.143120415258911, 0.162755851975246, 0.182865529959695,
0.20341701986178, 0.22438463188234, 0.245748013164318, 0.267491158005832,
0.289601702577961, 0.312070423267255, 0.337084153386502, 0.362632734261147,
0.388713550110491, 0.417009262625303, 0.446060748331539, 0.478344299849033,
0.511927776545623, 0.546903575783177, 0.583428286459313, 0.621755981338108,
0.662308487815083, 0.705837515898454), upper = c(0.0796782564120139,
0.104253197032666, 0.163162373925593, 0.311425838586527, 0.374432690497204,
0.386794184236729, 0.462447106364137, 0.462447106364137, 0.475081826536456,
0.475081826536456, 0.475081826536456, 0.538686209970986, 0.551932133039142,
0.565082314302923, 0.565082314302923, 0.565082314302923, 0.565082314302923,
0.581347998648697, 0.581347998648697, 0.598170095838594, 0.616628247575946,
0.616628247575946, 0.616628247575946, 0.616628247575946, 0.657208880749188,
0.0554260131286375, 0.0830100840055478, 0.0940622896679119, 0.104889543467743,
0.11551958346489, 0.125977767822471, 0.205368253636832, 0.214904894996087,
0.214904894996087, 0.233786022502375, 0.243138115767547, 0.252435578600051,
0.298192496252241, 0.307212268593429, 0.325133443864845, 0.342905511254632,
0.351738496831459, 0.369303313967178, 0.378164327666312, 0.386991801367172,
0.395786559611945, 0.404820623678952, 0.413819170217332, 0.42278305874121,
0.431713076032818, 0.449474317611162, 0.458455487152875, 0.458455487152875,
0.46740312211146, 0.476640870738304, 0.485841275433182, 0.495005029768766,
0.504308235077278, 0.513573240643691, 0.523180531581042, 0.53274457591725,
0.53274457591725, 0.542266095852977, 0.561184062577411, 0.570581579727844,
0.580160726343911, 0.599188192855639, 0.609136587487604, 0.648416591951278,
0.658109871602298, 0.668053287834676, 0.677940349143368, 0.688104008650237,
0.698204032116519, 0.711544781479331, 0.724715772241933, 0.738403133769579,
0.755603437116425, 0.755603437116425, 0.773673335614864, 0.811463880912856,
0.834261316418402, 0.834261316418402, 0.864305176695189, 0.891329588053304,
0.891329588053304, 0.164514540888494, 0.164514540888494, 0.164514540888494,
0.164514540888494, 0.164514540888494, 0.185453879855473, 0.214782436042548,
0.244858945502003, 0.274592902916402, 0.303763783420835, 0.303763783420835,
0.332343773644891, 0.360355238540763, 0.387832132523894, 0.414808316400823,
0.441314057995926, 0.467375240079267, 0.493013472868414, 0.518246474164134,
0.543088485840094, 0.56755064509021, 0.591641285440807, 0.615366163389952,
0.642996938577391, 0.669919078034907, 0.696160621236471, 0.724897048548371,
0.752630120302531, 0.78395657751485, 0.813600779732339, 0.841596636148257,
0.867931528334935, 0.892542509012415, 0.91530398695896, 0.935999137248638
)), row.names = c(NA, -121L), class = c("data.table", "data.frame"
))
</code>```

答:
Complete opacity appears to use alpha=1, not 0.  Only modifications to your code are (1) adding alpha=CIF as a mapping to geom_ribbon() and (2) adding the scale_alpha_manual line. Best practice might also be to add the breaks= argument to scale_alpha_manual to specify the correspondence between levels and values explicitly rather than relying on order ...

```<code>ggplot(res, aes(time, P)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = CIF, alpha=CIF))+
  geom_line(aes(color = CIF)) +
    scale_x_continuous(breaks = seq(0,100,10)) +
    scale_alpha_manual(values=c(1,0.2,0.2)) +
  coord_cartesian(xlim=c(0,100))
</code>```

Body:
Question: is it possible to assign different alpha-values to different fill's in a geom_ribbon()?

I have the following reproducible example of a cumulative incidence function

I have

> table(res$CIF)

CIF0 1; treatment=Control     CIF0 1; treatment=SSA    CIF0 1; treatment=SSTR
                       35                        61                        25

I would like complete opacity for res$CIF0 1; treatment=Control, ie. alpha=0, whereas the remaining two groups have alpha=0.2.

How can this be done?

ggplot(res, aes(time, P)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = CIF), alpha=0.2) +
  geom_line(aes(color = CIF)) +
  scale_x_continuous(breaks = seq(0,100,10)) +
  coord_cartesian(xlim=c(0,100))

Data sample

res <- structure(list(CIF = c("CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR",
"CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSTR", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA", "CIF0 1; treatment=SSA",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control", "CIF0 1; treatment=Control",
"CIF0 1; treatment=Control", "CIF0 1; treatment=Control"), P = c(0.0116279069767442,
0.0348837209302326, 0.0813953488372093, 0.209302325581395, 0.267441860465116,
0.27906976744186, 0.351162790697674, 0.351162790697674, 0.363405002193945,
0.363405002193945, 0.363405002193945, 0.425891290039491, 0.438998169929045,
0.452105049818598, 0.452105049818598, 0.452105049818598, 0.452105049818598,
0.467711841066396, 0.467711841066396, 0.483896661619669, 0.501488857873226,
0.501488857873226, 0.501488857873226, 0.501488857873226, 0.533914431204164,
0.008, 0.032, 0.0402735042735043, 0.0485470085470086, 0.0568205128205128,
0.0650940170940171, 0.131282051282051, 0.139555555555556, 0.139555555555556,
0.156102564102564, 0.164376068376068, 0.172649572649573, 0.214017094017094,
0.222290598290598, 0.238837606837607, 0.255384615384615, 0.26365811965812,
0.280205128205128, 0.288577126577126, 0.296949124949125, 0.305321123321123,
0.313905071018995, 0.322489018716867, 0.331072966414738, 0.33965691411261,
0.356824809508354, 0.365527978702029, 0.365527978702029, 0.374231147895705,
0.383194113184714, 0.392157078473723, 0.401120043762732, 0.410225278342043,
0.419330512921354, 0.428744399520302, 0.438158286119251, 0.438158286119251,
0.447572172718199, 0.466399945916096, 0.475813832515045, 0.485412305125737,
0.504609250347123, 0.514625047853932, 0.554688237881171, 0.564704035387981,
0.574976648215478, 0.585249261042975, 0.595807224226791, 0.606365187410608,
0.619660400308747, 0.632955613206886, 0.646804793309115, 0.66356959027497,
0.66356959027497, 0.681320551768229, 0.71935832639664, 0.742180991173687,
0.742180991173687, 0.771524417315605, 0.800867843457522, 0.800867843457522,
0.025, 0.025, 0.025, 0.025, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15,
0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3, 0.325, 0.35, 0.375,
0.4, 0.425, 0.45, 0.478333333333333, 0.506666666666667, 0.535,
0.565909090909091, 0.596818181818182, 0.631590909090909, 0.666363636363636,
0.701136363636364, 0.735909090909091, 0.770681818181818, 0.805454545454545,
0.840227272727273), time = c(0.1, 1, 2, 3, 4, 5, 6, 7.7, 8, 8.9,
9.7, 12, 13, 13.8, 15.6, 16, 18, 21, 21.8, 22, 26.2, 32, 47.2,
57, 75.9, 0.72, 1, 1.02, 1.08, 1.48, 1.87, 2, 2.43, 2.66, 2.76,
2.82, 2.83, 3, 3.06, 3.08, 3.57, 3.88, 4, 4.11, 4.23, 4.4, 5.06,
5.07, 5.29, 5.49, 6, 6.37, 6.41, 6.9, 7.48, 7.79, 8, 8.03, 9,
9.13, 9.2, 9.25, 10, 10.8, 11, 11.04, 12, 13, 13.47, 14.2, 15.05,
16.1, 18, 19, 21.1, 21.42, 23.1, 26.91, 29.84, 30.85, 36, 37,
50.4, 55, 60, 227.26, 0.23, 0.26, 0.49, 0.53, 0.69, 3.15, 3.25,
4.5, 5.12, 5.78, 6.67, 7.65, 7.79, 7.85, 9, 9.99, 11.37, 12.68,
13.11, 15.05, 15.83, 16.89, 18.17, 22.7, 23.59, 29.6, 32.65,
35.81, 43, 43.79, 45.37, 46.45, 46.65, 69.02, 105.16), lower = c(0.00164617019552282,
0.0113856737746599, 0.0396576469212214, 0.137397969022517, 0.186547499227902,
0.196621316727872, 0.260256711254436, 0.260256711254436, 0.271275320611526,
0.271275320611526, 0.271275320611526, 0.328365028488864, 0.340443606650536,
0.35260199321003, 0.35260199321003, 0.35260199321003, 0.35260199321003,
0.366602928781548, 0.366602928781548, 0.381138644331497, 0.396763300880135,
0.396763300880135, 0.396763300880135, 0.396763300880135, 0.419758773874353,
0.00113079397933524, 0.0121318162766967, 0.0169602104591103,
0.0221020257192824, 0.0274924721924664, 0.0330871802437624, 0.0825552954975503,
0.0891475380978586, 0.0891475380978586, 0.10252950910509, 0.109310958190052,
0.116148022092879, 0.151072486742553, 0.158189875311549, 0.17254320156191,
0.187045456692541, 0.194349432892335, 0.209057919001854, 0.216533612164684,
0.224041664416515, 0.231581290225624, 0.239310242224555, 0.247071853759351,
0.254865425506176, 0.262690312701882, 0.278431702879287, 0.286438278832329,
0.286438278832329, 0.294475403714247, 0.302741263754617, 0.311039845699379,
0.319370690508033, 0.327842676656013, 0.336347856846665, 0.345122677072548,
0.353933917141138, 0.353933917141138, 0.362781191618168, 0.380582536935198,
0.389536065805856, 0.398668454798478, 0.417044839259437, 0.426613603797864,
0.465317914150164, 0.475101203906211, 0.485129775477843, 0.495205813090998,
0.505553356441026, 0.515954049816092, 0.528422874133768, 0.541020866739871,
0.55413162171834, 0.569264211367809, 0.569264211367809, 0.585292041073961,
0.62005426996364, 0.640223402829866, 0.640223402829866, 0.664192334088305,
0.690689472196916, 0.690689472196916, 0.00355981698627006, 0.00355981698627006,
0.00355981698627006, 0.00355981698627006, 0.00355981698627006,
0.0127444761396915, 0.0248237564000704, 0.0387548083597935, 0.0540289278928447,
0.0703518337133965, 0.0703518337133965, 0.0875349177801499, 0.105448804967606,
0.124000413393049, 0.143120415258911, 0.162755851975246, 0.182865529959695,
0.20341701986178, 0.22438463188234, 0.245748013164318, 0.267491158005832,
0.289601702577961, 0.312070423267255, 0.337084153386502, 0.362632734261147,
0.388713550110491, 0.417009262625303, 0.446060748331539, 0.478344299849033,
0.511927776545623, 0.546903575783177, 0.583428286459313, 0.621755981338108,
0.662308487815083, 0.705837515898454), upper = c(0.0796782564120139,
0.104253197032666, 0.163162373925593, 0.311425838586527, 0.374432690497204,
0.386794184236729, 0.462447106364137, 0.462447106364137, 0.475081826536456,
0.475081826536456, 0.475081826536456, 0.538686209970986, 0.551932133039142,
0.565082314302923, 0.565082314302923, 0.565082314302923, 0.565082314302923,
0.581347998648697, 0.581347998648697, 0.598170095838594, 0.616628247575946,
0.616628247575946, 0.616628247575946, 0.616628247575946, 0.657208880749188,
0.0554260131286375, 0.0830100840055478, 0.0940622896679119, 0.104889543467743,
0.11551958346489, 0.125977767822471, 0.205368253636832, 0.214904894996087,
0.214904894996087, 0.233786022502375, 0.243138115767547, 0.252435578600051,
0.298192496252241, 0.307212268593429, 0.325133443864845, 0.342905511254632,
0.351738496831459, 0.369303313967178, 0.378164327666312, 0.386991801367172,
0.395786559611945, 0.404820623678952, 0.413819170217332, 0.42278305874121,
0.431713076032818, 0.449474317611162, 0.458455487152875, 0.458455487152875,
0.46740312211146, 0.476640870738304, 0.485841275433182, 0.495005029768766,
0.504308235077278, 0.513573240643691, 0.523180531581042, 0.53274457591725,
0.53274457591725, 0.542266095852977, 0.561184062577411, 0.570581579727844,
0.580160726343911, 0.599188192855639, 0.609136587487604, 0.648416591951278,
0.658109871602298, 0.668053287834676, 0.677940349143368, 0.688104008650237,
0.698204032116519, 0.711544781479331, 0.724715772241933, 0.738403133769579,
0.755603437116425, 0.755603437116425, 0.773673335614864, 0.811463880912856,
0.834261316418402, 0.834261316418402, 0.864305176695189, 0.891329588053304,
0.891329588053304, 0.164514540888494, 0.164514540888494, 0.164514540888494,
0.164514540888494, 0.164514540888494, 0.185453879855473, 0.214782436042548,
0.244858945502003, 0.274592902916402, 0.303763783420835, 0.303763783420835,
0.332343773644891, 0.360355238540763, 0.387832132523894, 0.414808316400823,
0.441314057995926, 0.467375240079267, 0.493013472868414, 0.518246474164134,
0.543088485840094, 0.56755064509021, 0.591641285440807, 0.615366163389952,
0.642996938577391, 0.669919078034907, 0.696160621236471, 0.724897048548371,
0.752630120302531, 0.78395657751485, 0.813600779732339, 0.841596636148257,
0.867931528334935, 0.892542509012415, 0.91530398695896, 0.935999137248638
)), row.names = c(NA, -121L), class = c("data.table", "data.frame"
))

Body:
Complete opacity appears to use alpha=1, not 0.  Only modifications to your code are (1) adding alpha=CIF as a mapping to geom_ribbon() and (2) adding the scale_alpha_manual line. Best practice might also be to add the breaks= argument to scale_alpha_manual to specify the correspondence between levels and values explicitly rather than relying on order ...

ggplot(res, aes(time, P)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = CIF, alpha=CIF))+
  geom_line(aes(color = CIF)) +
    scale_x_continuous(breaks = seq(0,100,10)) +
    scale_alpha_manual(values=c(1,0.2,0.2)) +
  coord_cartesian(xlim=c(0,100))


问:
node --max_old_space_size is not working
Node Version: 6.9.x

My application was giving me FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error.

So I tried changing the memory allocation using max_old_space_size flag

While executing my server.js, I am giving the --max_old_space_size=4096 argument.

However, it keeps crashing with same error as before. Also, I noticed the numbers in the error thrown while crashing. Looks like its still the default allocation of 1.4 GB.

Here's my error message:

```<code><--- Last few GCs --->

   84567 ms: Mark-sweep 1375.1 (1401.9) -> 1374.7 (1402.9) MB, 88.7 / 0.4 ms (+ 0.8 ms in 3 steps since start of marking, biggest step 0.5 ms) [allocation failure] [GC in old space requested].
   84648 ms: Mark-sweep 1374.7 (1402.9) -> 1374.7 (1402.9) MB, 81.3 / 0.0 ms [allocation failure] [GC in old space requested].
   84734 ms: Mark-sweep 1374.7 (1402.9) -> 1374.3 (1401.9) MB, 86.0 / 0.0 ms [last resort gc].
   84825 ms: Mark-sweep 1374.3 (1401.9) -> 1374.0 (1400.9) MB, 90.9 / 0.0 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x1bf641bcfb39 <JS Object>
    1: slowToString [buffer.js:460] [pc=0x2f7049a5d3d5] (this=0x93e46a2d6b1 <an Uint8Array with map 0x13be78e068d9>,encoding=0x1bf641bdd309 <String[4]: utf8>,start=53,end=3522765)
    2: toString [buffer.js:~488] [pc=0x2f70499b77a6] (this=0x93e46a2d6b1 <an Uint8Array with map 0x13be78e068d9>)
    3: arguments adaptor frame: 3->0
    4: deserialize [/opt/myServer/node_modu...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [node]
 2: 0x10d2fbc [node]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [node]
 5: v8::internal::Factory::NewRawOneByteString(int, v8::internal::PretenureFlag) [node]
 6: v8::internal::Factory::NewStringFromOneByte(v8::internal::Vector<unsigned char const>, v8::internal::PretenureFlag) [node]
 7: v8::internal::Factory::NewStringFromUtf8(v8::internal::Vector<char const>, v8::internal::PretenureFlag) [node]
 8: v8::String::NewFromUtf8(v8::Isolate*, char const*, v8::String::NewStringType, int) [node]
 9: node::StringBytes::Encode(v8::Isolate*, char const*, unsigned long, node::encoding) [node]
10: node::Buffer::Utf8Slice(v8::FunctionCallbackInfo<v8::Value> const&) [node]
11: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [node]
12: 0x9da914 [node]
13: 0x9daffe [node]
14: 0x2f7047a092a7
Aborted (core dumped)
</code>```

In the "Last few GCs" section, the memory size mentioned is always around 1404 MB. What am I doing wrong?

Is the system not able to allocated it any more memory?

答:
Now this flag is useless:

Versions of Node that are >= 12 should not need to use the
--optimize_for_size and --max_old_space_size flags because JavaScript heap limit will be based on available memory.

Body:
Node Version: 6.9.x

My application was giving me FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error.

So I tried changing the memory allocation using max_old_space_size flag

While executing my server.js, I am giving the --max_old_space_size=4096 argument.

However, it keeps crashing with same error as before. Also, I noticed the numbers in the error thrown while crashing. Looks like its still the default allocation of 1.4 GB.

Here's my error message:

<--- Last few GCs --->

   84567 ms: Mark-sweep 1375.1 (1401.9) -> 1374.7 (1402.9) MB, 88.7 / 0.4 ms (+ 0.8 ms in 3 steps since start of marking, biggest step 0.5 ms) [allocation failure] [GC in old space requested].
   84648 ms: Mark-sweep 1374.7 (1402.9) -> 1374.7 (1402.9) MB, 81.3 / 0.0 ms [allocation failure] [GC in old space requested].
   84734 ms: Mark-sweep 1374.7 (1402.9) -> 1374.3 (1401.9) MB, 86.0 / 0.0 ms [last resort gc].
   84825 ms: Mark-sweep 1374.3 (1401.9) -> 1374.0 (1400.9) MB, 90.9 / 0.0 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x1bf641bcfb39 <JS Object>
    1: slowToString [buffer.js:460] [pc=0x2f7049a5d3d5] (this=0x93e46a2d6b1 <an Uint8Array with map 0x13be78e068d9>,encoding=0x1bf641bdd309 <String[4]: utf8>,start=53,end=3522765)
    2: toString [buffer.js:~488] [pc=0x2f70499b77a6] (this=0x93e46a2d6b1 <an Uint8Array with map 0x13be78e068d9>)
    3: arguments adaptor frame: 3->0
    4: deserialize [/opt/myServer/node_modu...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [node]
 2: 0x10d2fbc [node]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [node]
 5: v8::internal::Factory::NewRawOneByteString(int, v8::internal::PretenureFlag) [node]
 6: v8::internal::Factory::NewStringFromOneByte(v8::internal::Vector<unsigned char const>, v8::internal::PretenureFlag) [node]
 7: v8::internal::Factory::NewStringFromUtf8(v8::internal::Vector<char const>, v8::internal::PretenureFlag) [node]
 8: v8::String::NewFromUtf8(v8::Isolate*, char const*, v8::String::NewStringType, int) [node]
 9: node::StringBytes::Encode(v8::Isolate*, char const*, unsigned long, node::encoding) [node]
10: node::Buffer::Utf8Slice(v8::FunctionCallbackInfo<v8::Value> const&) [node]
11: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [node]
12: 0x9da914 [node]
13: 0x9daffe [node]
14: 0x2f7047a092a7
Aborted (core dumped)

In the "Last few GCs" section, the memory size mentioned is always around 1404 MB. What am I doing wrong?

Is the system not able to allocated it any more memory?