问:
convert one class object into another using stream
I know this question can be misleading, if possible someone may correct it, I am not sure how to ask a question with this situation.

I am trying to Convert Class X into Class Y (here class Y contains fields of class X, but in different way, Eg:- Integer a, b; inside class X , converts to Map in class Y while other variables stay the same.),

using streams in java 8.
I am trying to return the final object to the UI part as json.
The project is done in spring boot.
Both Class X and Y contains the same objects, but Class Y is to make class X distinct
I am not familiar with streams.

Class X

```<code>public class X {

private final String thumbnailUrl;
private final Integer duration;
private final String contentId;
private final Date reportDate;
private final Integer count;

public X(Report report, int count) {
    this.thumbnailUrl = report.getContent().getThumbnailUrl();
    this.duration = report.getContent().getDuration();
    this.contentId = report.getContent().getContentId();
    this.reportDate = report.getReportDate();
    this.count = count;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public Integer getDuration() {
    return duration;
}

public String getContentId() {
    return contentId;
}

public Date getReportDate() {
    return reportDate;
}

public Integer getCount() {
    return count;
}

}
</code>```

Class Y

```<code>public class Y {

private final String thumbnailUrl;
private final Integer duration;
private final String contentId;
private final Map<Date, Integer> contentList;

public Y(X x, Map<Date, Integer> contentList) {
    this.thumbnailUrl = x.getThumbnailUrl();
    this.duration = x.getDuration();
    this.contentId = x.getContentId();
    this.contentList = contentList;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public Integer getDuration() {
    return duration;
}

public String getContentId() {
    return contentId;
}

public Map<Date, Integer> getContentList() {
    return contentList;
}

}
</code>```

This is what I am currently getting from class X

```<code>[
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-20",
    "count": 3
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-21",
    "count": 5
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-22",
    "count": 3
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-23",
    "count": 4
}
]
</code>```

I got the above json in postman after using this code and returning the final list.

```<code>List<X> x;
List<Y> y;

x = StreamSupport.stream(reportRepository
                .reportWithRoll(a, b, c).spliterator(), false)
                .map(report -> new X(report, report.getStartCount()))
                .collect(Collectors.toList());
</code>```

I want this to transformed into content of Class Y as below.
How can I achieve this with streams in Java?

```<code>[
    {
        "list": [
            {
                "2020-01-20": 3,
                "2020-01-21": 5,
                "2020-01-22": 3,
                "2020-01-23": 4
            }
        ],
        "thumbnailUrl": "a",
        "duration": 12,
        "contentId": "CNT10"
    }
]
</code>```

I tried this to get the above json format, but ended up getting duplicate data, for single contentId and error for multiple contentId

```<code>y = x.stream().map(
                rep -> {
                    Map<Date, Integer> contentList = x.stream().collect(
                            Collectors.toMap(X::getReportDate, X::getCount)
                    );
                    Y yy = new Y(rep, contentList);
                    return yy;
                }
        ).distinct().collect(Collectors.toList());
</code>```

I am combining the common date and count : key value pair into a single "list" for each unique "contentId" (each unique "contentId" will have its own "thumbnailUrl" and "duration" specific to it, so when I am referring only "contentId" as unique, it will include "thumbnailUrl" and "duration", only the date and count will be multiple for each of these).

答: Why complicate? Use Map Struts... You can convert one object in another in compile time. This is a really good Library and it's tested and used in Spring </p>

Body:
I know this question can be misleading, if possible someone may correct it, I am not sure how to ask a question with this situation.

I am trying to Convert Class X into Class Y (here class Y contains fields of class X, but in different way, Eg:- Integer a, b; inside class X , converts to Map in class Y while other variables stay the same.),

using streams in java 8.
I am trying to return the final object to the UI part as json.
The project is done in spring boot.
Both Class X and Y contains the same objects, but Class Y is to make class X distinct
I am not familiar with streams.

Class X

public class X {

private final String thumbnailUrl;
private final Integer duration;
private final String contentId;
private final Date reportDate;
private final Integer count;

public X(Report report, int count) {
    this.thumbnailUrl = report.getContent().getThumbnailUrl();
    this.duration = report.getContent().getDuration();
    this.contentId = report.getContent().getContentId();
    this.reportDate = report.getReportDate();
    this.count = count;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public Integer getDuration() {
    return duration;
}

public String getContentId() {
    return contentId;
}

public Date getReportDate() {
    return reportDate;
}

public Integer getCount() {
    return count;
}

}

Class Y

public class Y {

private final String thumbnailUrl;
private final Integer duration;
private final String contentId;
private final Map<Date, Integer> contentList;

public Y(X x, Map<Date, Integer> contentList) {
    this.thumbnailUrl = x.getThumbnailUrl();
    this.duration = x.getDuration();
    this.contentId = x.getContentId();
    this.contentList = contentList;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public Integer getDuration() {
    return duration;
}

public String getContentId() {
    return contentId;
}

public Map<Date, Integer> getContentList() {
    return contentList;
}

}

This is what I am currently getting from class X

[
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-20",
    "count": 3
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-21",
    "count": 5
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-22",
    "count": 3
},
{
    "thumbnailUrl": "a",
    "duration": 12,
    "contentId": "CNT10",
    "reportDate": "2020-01-23",
    "count": 4
}
]

I got the above json in postman after using this code and returning the final list.

List<X> x;
List<Y> y;

x = StreamSupport.stream(reportRepository
                .reportWithRoll(a, b, c).spliterator(), false)
                .map(report -> new X(report, report.getStartCount()))
                .collect(Collectors.toList());

I want this to transformed into content of Class Y as below.
How can I achieve this with streams in Java?

[
    {
        "list": [
            {
                "2020-01-20": 3,
                "2020-01-21": 5,
                "2020-01-22": 3,
                "2020-01-23": 4
            }
        ],
        "thumbnailUrl": "a",
        "duration": 12,
        "contentId": "CNT10"
    }
]

I tried this to get the above json format, but ended up getting duplicate data, for single contentId and error for multiple contentId

y = x.stream().map(
                rep -> {
                    Map<Date, Integer> contentList = x.stream().collect(
                            Collectors.toMap(X::getReportDate, X::getCount)
                    );
                    Y yy = new Y(rep, contentList);
                    return yy;
                }
        ).distinct().collect(Collectors.toList());

I am combining the common date and count : key value pair into a single "list" for each unique "contentId" (each unique "contentId" will have its own "thumbnailUrl" and "duration" specific to it, so when I am referring only "contentId" as unique, it will include "thumbnailUrl" and "duration", only the date and count will be multiple for each of these).


来源: stackexchange

问:
Angular 9 ng new myapp gives error The Schematic workflow failed
I have angular 9 installed

Angular CLI: 9.0.1 Node: 13.8.0 OS: win32 x64

Angular: ... Ivy Workspace:

Package                      Version

@angular-devkit/architect    0.900.1

  @angular-devkit/core         9.0.1

  @angular-devkit/schematics   9.0.1

  @schematics/angular          9.0.1

  @schematics/update           0.900.1

  rxjs                         6.5.3

Everytime i try to create a new project with ng new, I'm getting the message

Installing packages...npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
  npm ERR! Unexpected end of JSON input while parsing near '...pm-signature":"-----B'
  npm ERR! A complete log of this run can be found in:
  npm ERR! C:\Users\Lijo John Daniel\AppData\Roaming\npm-cache_logs\2020-02-12T09_52_57_342Z-debug.log
  × Package install failed, see above.
  The Schematic workflow failed. See above.

I have tried re-installing angular and even node but issue still remains

My OS version is Win 10 v.1909 build 18363.592. Can someone help me with this?

答:
I had this issue since yesterday, tried all of this and it did not work. Then I installed yarn, and configured angular cli to use yarn as the packagemanager by running this command
ng config -g cli.packageManager yarn, and it worked.

ContentLicense: CC BY-SA 4.0


问:
Knit only until a specific chunk
Is there a way to knit a html_document until a specific chunk?

Suppose I have this .Rmd and I want only to knit a html_document until the cars chunk:

```<code>---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

<h2>R Markdown</h2>

<p>This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.</p>

<p>When you click the <strong>Knit</strong> button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>

```summary(cars)
```

<h2>Including Plots</h2>

<p>You can also embed plots, for example:</p>

```plot(pressure)
```

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

答:
I find a way, but isn't so pretty.
I have selected all the code and pressed Ctrl + Shift + C, so commented all the lines:

```<code>---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

<h2>R Markdown</h2>

<p>This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.</p>

<p>When you click the <strong>Knit</strong> button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>

```summary(cars)
```

```

<!-- plot(pressure) -->
<!-- ``` -->

</code>```

Title: Knit only until a specific chunk

Body:
Is there a way to knit a html_document until a specific chunk?

Suppose I have this .Rmd and I want only to knit a html_document until the cars chunk:

---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)

Including Plots

You can also embed plots, for example:

plot(pressure)

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Body:
I find a way, but isn't so pretty.
I have selected all the code and pressed Ctrl + Shift + C, so commented all the lines:

---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
</code></pre>

<h2>R Markdown</h2>

<p>This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <a href="http://rmarkdown.rstudio.com" rel="nofollow noreferrer">http://rmarkdown.rstudio.com</a>.</p>

<p>When you click the <strong>Knit</strong> button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>

<pre><code>summary(cars)
</code></pre>

<pre><code><!-- ## Including Plots -->
<!-- You can also embed plots, for example: -->
<!-- ```{r pressure, echo=FALSE} -->
<!-- plot(pressure) -->
<!-- ``` -->
<!-- Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. -->


问:
What happens when you write to a register with the same configuration?
I'm working with the STM32L432KC and am relatively new to the embedded world.  What happens if I write to a configuration register, wait some time, and then write to the register again with the same configuration.  Does this have any effects?

For reference, I am using the STM32L432KC microcontroller.  The register in question is the Reset and Clock Control (RCC), AHB2 Peripheral Clock Enable Register (RCC_AHB2ENR).  I have a function that enables the clock for a GPIO port, by OR'ing in a bit.  I am wondering if calling the function while the pin is active will have any effects.

答:
There is no generic answer for all registers on all devices.  The only correct course is to consult the data sheet or reference manual for the part concerned.

In the specific case of STM32L432 RCC_AHB2ENR all used bits are specified as "set and cleared by software" with no specific hardware action on read/write.  This is true I believe for the RCC_AHB2ENR on all STM32.  Note however that the unused bits are reserved and should not be set to any value other then the reset value - also defined in the reference manual and in this case all zero.

Some registers change value under hardware control, so re-writing a previously written value may have an effect.  A simple example on your part is TIM1_CNT where if TIM1 is running the counter will have changed and rewriting it will effect its period and any capture/compare events or event output or PWM it may be used for.


问:
Asp.Net core Repository and Unit Of Work Pattern for Posting an entity
Trying to use an async method as I used to do with Repository Pattern to post an entity, but this time I wanted to integrate the Unit Of Work pattern, here is my interface:

```<code>public interface IUnitOfWork : IDisposable
{
    . . .
    void Save();
}
</code>```

And its implementation:

```<code>public class UnitOfWork : IUnitOfWork
{
    private readonly DataContext _db;

    public UnitOfWork(DataContext db)
    {
        _db = db;
        . . .
    }
    . . .
    public void Dispose()
    {
        _db.Dispose();
    }

    public void Save()
    {
        _db.SaveChanges();
    }
}
</code>```

And here is my method:

```<code>    [HttpPost]
    public async Task<IActionResult> CreateItem(string userId, ItemForCreationDto itemForCreationDto)
    {
        if (userId != User.FindFirst(ClaimTypes.NameIdentifier).Value)
            return Unauthorized();

        itemForCreationDto.UserId = userId;
        var item = _mapper.Map<Item>(itemForCreationDto);

        if (item == null)
            return BadRequest("Could not find item");

        _uow.Item.Add(item);

        if (await _uow.Save())                                       <--- Error here
        {
            var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
            return CreatedAtRoute("GetItem",
                new { userId, id = item.Id }, itemToReturn);
        }

        throw new Exception("Creating the item failed on save");
    }
</code>```

But I got the following erors:

Can't wait for 'void'

That's because I am trying to call a Save() method which is void from an async HttpPost method, I know that makes no sens, but till now I could not find how to implement that for this special case.
When I tried removing the await I got the following error:

Unable to implicitly convert type 'void' to 'bool'

Any suggestion on how to implement that ?

答:
Either refactor the interface to be async or add an additional member

```<code>public interface IUnitOfWork : IDisposable {

    //. . .

    Task<bool> SaveAsync();
}
</code>```

that can probably wraps the context's asynchronous API in the implementation if one exists

```<code>public async Task<bool> SaveAsync() {
    int count = await _db.SaveChangesAsync();
    return count > 0;
}
</code>```

allowing for the desired functionality

```<code>//...

if (await _uow.SaveAsync()){
    var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
    return CreatedAtRoute("GetItem", new { userId, id = item.Id }, itemToReturn);
}

//...
</code>```

Body:
Trying to use an async method as I used to do with Repository Pattern to post an entity, but this time I wanted to integrate the Unit Of Work pattern, here is my interface:

public interface IUnitOfWork : IDisposable
{
    . . .
    void Save();
}

And its implementation:

public class UnitOfWork : IUnitOfWork
{
    private readonly DataContext _db;

    public UnitOfWork(DataContext db)
    {
        _db = db;
        . . .
    }
    . . .
    public void Dispose()
    {
        _db.Dispose();
    }

    public void Save()
    {
        _db.SaveChanges();
    }
}

And here is my method:

    [HttpPost]
    public async Task<IActionResult> CreateItem(string userId, ItemForCreationDto itemForCreationDto)
    {
        if (userId != User.FindFirst(ClaimTypes.NameIdentifier).Value)
            return Unauthorized();

        itemForCreationDto.UserId = userId;
        var item = _mapper.Map<Item>(itemForCreationDto);

        if (item == null)
            return BadRequest("Could not find item");

        _uow.Item.Add(item);

        if (await _uow.Save())                                       <--- Error here
        {
            var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
            return CreatedAtRoute("GetItem",
                new { userId, id = item.Id }, itemToReturn);
        }

        throw new Exception("Creating the item failed on save");
    }

But I got the following erors:

Can't wait for 'void'

That's because I am trying to call a Save() method which is void from an async HttpPost method, I know that makes no sens, but till now I could not find how to implement that for this special case.
When I tried removing the await I got the following error:

Unable to implicitly convert type 'void' to 'bool'

Any suggestion on how to implement that ?

Body:
Either refactor the interface to be async or add an additional member

public interface IUnitOfWork : IDisposable {

    //. . .

    Task<bool> SaveAsync();
}

that can probably wraps the context's asynchronous API in the implementation if one exists

public async Task<bool> SaveAsync() {
    int count = await _db.SaveChangesAsync();
    return count > 0;
}

allowing for the desired functionality

//...

if (await _uow.SaveAsync()){
    var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
    return CreatedAtRoute("GetItem", new { userId, id = item.Id }, itemToReturn);
}

//...


问:
Shifting a graphics Path object over
In Java, Android specifically, how do I transform a Path object over 100 pixels? Like in C#, I would use the following code to do this:

```<code>// Create a path and add and ellipse.
GraphicsPath myPath = new GraphicsPath();
myPath.AddEllipse(0, 0, 100, 200);

// Draw the starting position to screen.
e.Graphics.DrawPath(Pens.Black, myPath);

// Move the ellipse 100 points to the right.
Matrix translateMatrix = new Matrix();
translateMatrix.Translate(100, 0);
myPath.Transform(translateMatrix);

// Draw the transformed ellipse to the screen.
e.Graphics.DrawPath(new Pen(Color.Red, 2), myPath);
</code>```

How do I do this in Android? I already have my Path object:

```<code>@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint pnt = new Paint();
    Path p = new Path();

    pnt.setStyle(Paint.Style.STROKE);
    pnt.setColor(Color.WHITE);

    p.moveTo(97.4f, 87.6f);
    p.lineTo(97.4f, 3.8f);

    p.lineTo(-1.2f, 1.2f);
    p.lineTo(-0.4f,-0.4f);

    p.lineTo(-0.4f,87f);

    p.lineTo(97.4f, 87.6f);
    p.close();

    canvas.drawPath(p, pnt);
}
</code>```

What do you I need to do in order to shift my Path object over 100 pixels?

答:
It's almost the same:

```<code>Matrix translateMatrix = new Matrix();
translateMatrix.setTranslate(100,0);
p.transform(translateMatrix);
</code>```

I didn't test it, just looked into API.

ContentLicense: CC BY-SA 3.0

Title: Shifting a graphics Path object over

Body:
In Java, Android specifically, how do I transform a Path object over 100 pixels? Like in C#, I would use the following code to do this:

// Create a path and add and ellipse.
GraphicsPath myPath = new GraphicsPath();
myPath.AddEllipse(0, 0, 100, 200);

// Draw the starting position to screen.
e.Graphics.DrawPath(Pens.Black, myPath);

// Move the ellipse 100 points to the right.
Matrix translateMatrix = new Matrix();
translateMatrix.Translate(100, 0);
myPath.Transform(translateMatrix);

// Draw the transformed ellipse to the screen.
e.Graphics.DrawPath(new Pen(Color.Red, 2), myPath);

How do I do this in Android? I already have my Path object:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint pnt = new Paint();
    Path p = new Path();

    pnt.setStyle(Paint.Style.STROKE);
    pnt.setColor(Color.WHITE);

    p.moveTo(97.4f, 87.6f);
    p.lineTo(97.4f, 3.8f);

    p.lineTo(-1.2f, 1.2f);
    p.lineTo(-0.4f,-0.4f);

    p.lineTo(-0.4f,87f);

    p.lineTo(97.4f, 87.6f);
    p.close();

    canvas.drawPath(p, pnt);
}

What do you I need to do in order to shift my Path object over 100 pixels?

Body:
It's almost the same:

Matrix translateMatrix = new Matrix();
translateMatrix.setTranslate(100,0);
p.transform(translateMatrix);

I didn't test it, just looked into API.


问:
Pass ArrayList object to fragment
I'm having a hard time solving this issue. I'm trying to send 3 different arraylists of custom objects to a fragment from expandable list view click. Here is expandable list view code(I have only included the first group position and children, but in reality there are more):

```<code>*/
public class MyWorkout extends BaseActivity{

ExpandableListView expandableListView;
HashMap<String, List<String>> Workouts_details;
List<String> Workout_list;
WorkoutsAdapter mAdapter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_workout);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();

    expandableListView = (ExpandableListView) findViewById(R.id.listViewWorkouts);
    Workouts_details = DataProvider.getInfo();
    Workout_list = new ArrayList<>(Workouts_details.keySet());
    mAdapter = new WorkoutsAdapter(this, Workouts_details, Workout_list);

    expandableListView.setAdapter(mAdapter);

    expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            if (groupPosition == 0) {
                if (childPosition == 0) {
                    Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }
                if (childPosition == 1) {
                  Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }
</code>```

From there, each childClick sends the app to WorkoutDaysActivity, where 3 tabs are set up with fragments. Here is the code to this class:

```<code>public class WorkoutDaysActivity extends BaseActivity{

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.workout_days);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();

    ViewPager vp = (ViewPager) findViewById(R.id.view_pager);
    this.addPages(vp);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setupWithViewPager(vp);
    tabLayout.setOnTabSelectedListener(listener(vp));

}

//ADD ALL PAGES
private void addPages(ViewPager pager) {
    MyFragPagerAdapter adapter = new  MyFragPagerAdapter(getSupportFragmentManager());
    Intent intent = getIntent();
    String workout = intent.getStringExtra("workout");
    Bundle args = new Bundle();
    args.putString("workout", workout);

    MondayFragment mondayFragment = new MondayFragment();
    mondayFragment.setArguments(args);
    adapter.addPage(mondayFragment);
    WedFragment wedFragment = new WedFragment();
    wedFragment.setArguments(args);
    adapter.addPage(wedFragment);
    FridayFragment fridayFragment = new FridayFragment();
    fridayFragment.setArguments(args);
    adapter.addPage(fridayFragment);
     pager.setAdapter(adapter);
}

private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}
 }
</code>```

Then from there, I have the 3 tab fragment classes. Each  class looks like this:

```<code>public class WedFragment extends Fragment {

Bundle args = getArguments();
String workout3 = args.getString("workout");

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.wed_fragment, null);

//        //RECYCLERVIEW
    RecyclerView rv = (RecyclerView) view.findViewById(R.id.mRecyclerWed);
    rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    rv.setAdapter(new MyRecyclerAdapter(this.getActivity(), getWedWorkout()));

    return view;

}

private ArrayList<Workout> getWedWorkout() {
    //COLLECTION OF MONDAY WORKOUT

    ArrayList<Workout> workout = new ArrayList<>();
    switch(workout3) {
        case "w29w1" : {
            Workout workouts = new Workout("Bench", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Bench", "70", "5", "175", false);
            workout.add(workouts);

            break;}
        case "w29w2" :{
            Workout workouts = new Workout("Squat", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Squat", "70", "5", "175", false);
            workout.add(workouts);

        break;}
    } return workout;

    //SINGLE EXERCISE

}

@Override
public String toString() {
    return "Wednesday";
}
}
</code>```

EDIT: I've edited my post, this is why I was trying to do. In my mind it should work, in reality it does not. I get this error when the app tries to open the fragment and crashes:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bestworkouts.sheikoworkout/com.bestworkouts.sheikoworkout.WorkoutDaysActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.bestworkouts.sheikoworkout.Fragments.WedFragment.<init>(WedFragment.java:24)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.addPages(WorkoutDaysActivity.java:47)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.onCreate(WorkoutDaysActivity.java:27)
                                                                                at android.app.Activity.performCreate(Activity.java:6876)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
</code>```

答:
As a workaround it is sometimes easy to convert your array list to string (or JSON string) and send by

```<code>bundle.putString()
</code>```

and then, in fragment, parse the string back to array list.

Title: Pass ArrayList object to fragment

Body:
I'm having a hard time solving this issue. I'm trying to send 3 different arraylists of custom objects to a fragment from expandable list view click. Here is expandable list view code(I have only included the first group position and children, but in reality there are more):

*/
public class MyWorkout extends BaseActivity{

ExpandableListView expandableListView;
HashMap<String, List<String>> Workouts_details;
List<String> Workout_list;
WorkoutsAdapter mAdapter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_workout);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();

    expandableListView = (ExpandableListView) findViewById(R.id.listViewWorkouts);
    Workouts_details = DataProvider.getInfo();
    Workout_list = new ArrayList<>(Workouts_details.keySet());
    mAdapter = new WorkoutsAdapter(this, Workouts_details, Workout_list);

    expandableListView.setAdapter(mAdapter);

    expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            if (groupPosition == 0) {
                if (childPosition == 0) {
                    Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }
                if (childPosition == 1) {
                  Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }

From there, each childClick sends the app to WorkoutDaysActivity, where 3 tabs are set up with fragments. Here is the code to this class:

public class WorkoutDaysActivity extends BaseActivity{

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.workout_days);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();

    ViewPager vp = (ViewPager) findViewById(R.id.view_pager);
    this.addPages(vp);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setupWithViewPager(vp);
    tabLayout.setOnTabSelectedListener(listener(vp));

}

//ADD ALL PAGES
private void addPages(ViewPager pager) {
    MyFragPagerAdapter adapter = new  MyFragPagerAdapter(getSupportFragmentManager());
    Intent intent = getIntent();
    String workout = intent.getStringExtra("workout");
    Bundle args = new Bundle();
    args.putString("workout", workout);

    MondayFragment mondayFragment = new MondayFragment();
    mondayFragment.setArguments(args);
    adapter.addPage(mondayFragment);
    WedFragment wedFragment = new WedFragment();
    wedFragment.setArguments(args);
    adapter.addPage(wedFragment);
    FridayFragment fridayFragment = new FridayFragment();
    fridayFragment.setArguments(args);
    adapter.addPage(fridayFragment);
     pager.setAdapter(adapter);
}

private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}
 }

Then from there, I have the 3 tab fragment classes. Each  class looks like this:

public class WedFragment extends Fragment {

Bundle args = getArguments();
String workout3 = args.getString("workout");

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.wed_fragment, null);

//        //RECYCLERVIEW
    RecyclerView rv = (RecyclerView) view.findViewById(R.id.mRecyclerWed);
    rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    rv.setAdapter(new MyRecyclerAdapter(this.getActivity(), getWedWorkout()));

    return view;

}

private ArrayList<Workout> getWedWorkout() {
    //COLLECTION OF MONDAY WORKOUT

    ArrayList<Workout> workout = new ArrayList<>();
    switch(workout3) {
        case "w29w1" : {
            Workout workouts = new Workout("Bench", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Bench", "70", "5", "175", false);
            workout.add(workouts);

            break;}
        case "w29w2" :{
            Workout workouts = new Workout("Squat", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Squat", "70", "5", "175", false);
            workout.add(workouts);

        break;}
    } return workout;

    //SINGLE EXERCISE

}

@Override
public String toString() {
    return "Wednesday";
}
}

EDIT: I've edited my post, this is why I was trying to do. In my mind it should work, in reality it does not. I get this error when the app tries to open the fragment and crashes:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bestworkouts.sheikoworkout/com.bestworkouts.sheikoworkout.WorkoutDaysActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.bestworkouts.sheikoworkout.Fragments.WedFragment.<init>(WedFragment.java:24)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.addPages(WorkoutDaysActivity.java:47)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.onCreate(WorkoutDaysActivity.java:27)
                                                                                at android.app.Activity.performCreate(Activity.java:6876)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)

Body:
As a workaround it is sometimes easy to convert your array list to string (or JSON string) and send by

bundle.putString()

and then, in fragment, parse the string back to array list.


问:
CollectionConverters always return the original source object?
CollectionConverters API states

In all cases, converting from a source type to a target type and back
  again will return the original source object.

This does not seem to be always true. For example, in the following case it is indeed true

```<code>val orig = ListBuffer(1,2,3)
assert(orig.asJava.asScala eq orig)   // OK
</code>```

however here the assertion fails

```<code>val orig = ListBuffer(1,2,3).asJava
assert(orig.asScala.asJava eq orig)   // Boom!
</code>```

Changing to a List instead of ListBuffer the assertion passes

```<code>val orig = List(1,2,3).asJava
assert(orig.asScala.asJava eq orig)   // OK
</code>```

Does the middle case mean a copy was made? If so, what are the precise rules on when is a copy made hence there being a performance hit?

答:
asJava and asScala never copy entire collections, but they do instantiate wrappers.

After val orig = ListBuffer(1,2,3).asJava, orig is a wrapper, an instance of class scala.collection.convert.JavaCollectionWrappers$MutableBufferWrapper.

After the next .asScala, you get the original ListBuffer back.

Now you call .asJava again. At this point, there is no other possible outcome than for a new wrapper to be instantiated, not (as you discovered) eq to the previous wrapper.

The guarantee that you quote applies to original collections, not to conversion wrappers. Perhaps the wording ought to be clearer about that.

Body:
CollectionConverters API states

In all cases, converting from a source type to a target type and back
  again will return the original source object.

This does not seem to be always true. For example, in the following case it is indeed true

val orig = ListBuffer(1,2,3)
assert(orig.asJava.asScala eq orig)   // OK

however here the assertion fails

val orig = ListBuffer(1,2,3).asJava
assert(orig.asScala.asJava eq orig)   // Boom!

Changing to a List instead of ListBuffer the assertion passes

val orig = List(1,2,3).asJava
assert(orig.asScala.asJava eq orig)   // OK

Does the middle case mean a copy was made? If so, what are the precise rules on when is a copy made hence there being a performance hit?


问:
Jenkins : Use "Build after other projects are built" and "Build periodically" at the same time
I have two jobs, p1 and p2.

Conditions that trigger p2:

p1 build is completed

Every Monday

But I know "Build after other projects are built" and "Build periodically" do not trigger at the same time.
Is there any way to solve this?

答: Yes: Make a job p3 than just triggers job p2 when p1 is completed. And schedule p2 to run periodically.</p>


问:
Why does barista/coffeescript not tell you what is wrong when you have an error?
I am trying out coffeescript with barista, and I am not having a good time with it.

For some reason, whenever I make a change to a .coffee file, barista complains that there is a compile error except for the most trivial of cases (like a simple call to 'alert').

When I get these error messages, it doesn't actually tell me what's wrong - it just says that there is a 'V8: JSError'. There are no line numbers. Nothing.

To fix these errors, I CTRL-C the Rails server and restart it... and all is well... but making any change at all to the .coffee file just causes Barista to throw yet another compiler error - and the process repeats. Even if I add correct Coffeescript code, it still throws a compiler error. I have no idea why.

How can anyone program like this? I need good feedback or I am totally lost. Most of the time, the .coffee file contains no error because it compiles after I restart the server.

I also prefer fast feedback, or I get impatient. One of the attractions to developing with rails is that everything is pretty immediate. This coffeescript thing though has to be as bad as working in Java.

As much as I hate javascript, at least the feedback is more responsive and I don't have to restart the server.

Did I just set this up wrong? Is this really what it's like to code in coffeescript? If it is... then why is this being forced on everyone in rails 3.1?

I'm just not having a good day today. I'm sorry if this comes off as bad. I've been spending hours with coffeescript and I honestly am not getting very far. Programming without detailed error messages and being forced to restart the server to see my changes take effect reminds me of Java... and that's why I stopped using it in the first place.

:(

答:
What's going on is that when Barista encounters a compile-time error in your CoffeeScript code, it takes that error message and uses it as the JS output. Since that error message is invalid JS, you get a vague error from your browser. If you can think of a better way to do this, you should raise an issue to suggest it.

For now, what you should do is either

View the source of the page, get the address of the JS file, and open it up directly in your browser, or

Use your text editor's “Build” feature (e.g. Cmd+B in TextMate) to show the compiled output, or compilation errors, of the responsible CoffeeScript file, or

Use the barista_growl plugin so that you get a Growl notification when a compilation error occurs.

None of the above is ideal, but browser support for CoffeeScript debugging is coming...


问:
Cherry-pick modules with Rollup and ES Modules?
With lodash-es, we can cherry-pick modules like this: import drop from 'lodash/drop'; This way only drop gets used and nothing else.

How do I achieve the same thing with Rollup?

I'm configuring a react & typescript ui library to be used in two create-react-app projects. I learned that using esm is best for my use case and it's the most affective way to achieve treeshaking with Rollup. However, when I use my library, I'm importing like this: import { someComponent }from 'my-ui-library'; is this singling out someComponent like the cherry-pick method above. Does the syntax matter?

Here is my rollup.config.js:

```<code>import babel from 'rollup-plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import svgr from '@svgr/rollup';
import url from '@rollup/plugin-url';
import json from '@rollup/plugin-json';
import external from 'rollup-plugin-peer-deps-external';
import includePaths from 'rollup-plugin-includepaths';

const pkg = require('./package.json');

export default {
  cache: false,
  input: 'src/index.ts',
  output: [{ file: pkg.module, format: 'esm' }],
  treeshake: true,
  plugins: [
    external({
      preferBuiltins: false,
    }),
    babel({
      exclude: /node_modules/,
      plugins: ['external-helpers'],
      externalHelpers: true, // Exclude babel helpers.
    }),
    json(),
    resolve(),
    svgr({
      ref: true,
      svgo: false,
    }),
    typescript({
      clean: true,
      typescript: require('typescript'),
    }),
    url(),
    includePaths({
      paths: ['src'],
    }),
  ],
};
</code>```

答:
There seems to be a few catches when tree-shaking ESM packages. The first catch is that tree shaking only works in production and the second catch is that your package.json must contain a sideEffects: false property. Unfortunately, in development, tree shaking still imports the entire library to retrieve the named export. Click here more info about webpack tree-shaking.

For example (in development): import screenshot exmaple

In the example above, I'm importing a named export called defaultLayoutCommands; however, it still shows that all of the library was imported, even though webpack is utilizing the esm file. However, if I separate the file and import that directly, then it shows the smaller import size. In production, this should tree-shake import the defaultLayoutCommands and be just like the second import example. That said, tree-shaking only works with webpack AND ESM.

When working with CJS/UMD/AMD, tree-shaking won't work. Instead, you'll have to combine all of your exports to a single class/object (like an exports object). Then using ES6 destructuring, you can pull off that method.

For example, lodash has all the functions within a single file, for example:

```<code>    function throttle(func, wait, options) {
      var leading = true,
      trailing = true;

      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = 'leading' in options ? !!options.leading : leading;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
       'leading': leading,
       'maxWait': wait,
       'trailing': trailing
     });
   }
</code>```

And then attaches that function as a method to an object:

```<code>lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
...
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
...etc
</code>```

And then using an IIFE exports the lodash object. The nice thing about this is that you can require multiple named imports at once:

```<code>const { get, debounce, isEmpty } = require("lodash");
</code>```

The disadvantage is that you're requiring the entire lodash object. So, to get around this, they have separate files (and/or npm packages!!!) to limit the imports to just what's needed. So, they have included additional files like this in the root package folder:

```<code>...js
get.js
debounce.js
isEmpty.js
...js
</code>```

However, the disadvantage with this, is that you'll now have three imports:

```<code>const get = require("lodash/get");
const debounce = require("lodash/debounce");
const isEmpty = require("lodash/isEmpty");
</code>```

But! You'll have an overall smaller import size... however, the package size is larger! So to mitigate this, they broke up some of the popular methods into their own separate packages: lodash.get, lodash.debounce, and lodash.isEmpty!

So, in summation, if you don't plan on utilizing CJS/UMD/AMD (like lodash does), then tree-shaking will work as expected in production when using webpack and ESM packages within the client. However, if you are including additional builds for more compatibility, then you'll have to create an array of rollup configs with different inputs and different outputs.

For example:

```<code>const resolutions = {
    globals: {
        react: "React",
        "react-is": "reactIs",
    },
    exports: "named",
};

export default [
  {
    input: "./src/index.js", // this transforms the entire source
    output: [
        {
            file: pkg.main,
            format: "cjs",
            ...resolutions,
        },
        {
            file: pkg.fallback,
            format: "umd",
            name: "My-Example-Library",
            ...resolutions,
        },
        {
            file: pkg.module,
            format: "esm",
            ...resolutions,
        },
    ],
    ...etc
  },
  {
    input: "./src/components/example.js", // this transforms just an "example.js" file and ouputs to a "dist/example.[build].js" file
    output: [
        {
            file: "dist/example.cjs.js,
            format: "cjs",
            ...resolutions,
        },
        {
            file: dist/example.umd.js,
            format: "umd",
            name: "My-Example",
            ...resolutions,
        },
    ],
    ...etc
  }
]
</code>```

More info about use cases for the different builds can be found here and an example Rollup config can be found here.

Body:
With lodash-es, we can cherry-pick modules like this: import drop from 'lodash/drop'; This way only drop gets used and nothing else.

How do I achieve the same thing with Rollup?

I'm configuring a react & typescript ui library to be used in two create-react-app projects. I learned that using esm is best for my use case and it's the most affective way to achieve treeshaking with Rollup. However, when I use my library, I'm importing like this: import { someComponent }from 'my-ui-library'; is this singling out someComponent like the cherry-pick method above. Does the syntax matter?

Here is my rollup.config.js:

import babel from 'rollup-plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import svgr from '@svgr/rollup';
import url from '@rollup/plugin-url';
import json from '@rollup/plugin-json';
import external from 'rollup-plugin-peer-deps-external';
import includePaths from 'rollup-plugin-includepaths';

const pkg = require('./package.json');

export default {
  cache: false,
  input: 'src/index.ts',
  output: [{ file: pkg.module, format: 'esm' }],
  treeshake: true,
  plugins: [
    external({
      preferBuiltins: false,
    }),
    babel({
      exclude: /node_modules/,
      plugins: ['external-helpers'],
      externalHelpers: true, // Exclude babel helpers.
    }),
    json(),
    resolve(),
    svgr({
      ref: true,
      svgo: false,
    }),
    typescript({
      clean: true,
      typescript: require('typescript'),
    }),
    url(),
    includePaths({
      paths: ['src'],
    }),
  ],
};

Body:
There seems to be a few catches when tree-shaking ESM packages. The first catch is that tree shaking only works in production and the second catch is that your package.json must contain a sideEffects: false property. Unfortunately, in development, tree shaking still imports the entire library to retrieve the named export. Click here more info about webpack tree-shaking.

For example (in development): import screenshot exmaple

In the example above, I'm importing a named export called defaultLayoutCommands; however, it still shows that all of the library was imported, even though webpack is utilizing the esm file. However, if I separate the file and import that directly, then it shows the smaller import size. In production, this should tree-shake import the defaultLayoutCommands and be just like the second import example. That said, tree-shaking only works with webpack AND ESM.

When working with CJS/UMD/AMD, tree-shaking won't work. Instead, you'll have to combine all of your exports to a single class/object (like an exports object). Then using ES6 destructuring, you can pull off that method.

For example, lodash has all the functions within a single file, for example:

    function throttle(func, wait, options) {
      var leading = true,
      trailing = true;

      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = 'leading' in options ? !!options.leading : leading;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
       'leading': leading,
       'maxWait': wait,
       'trailing': trailing
     });
   }

And then attaches that function as a method to an object:

lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
...
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
...etc

And then using an IIFE exports the lodash object. The nice thing about this is that you can require multiple named imports at once:

const { get, debounce, isEmpty } = require("lodash");

The disadvantage is that you're requiring the entire lodash object. So, to get around this, they have separate files (and/or npm packages!!!) to limit the imports to just what's needed. So, they have included additional files like this in the root package folder:

...js
get.js
debounce.js
isEmpty.js
...js

However, the disadvantage with this, is that you'll now have three imports:

const get = require("lodash/get");
const debounce = require("lodash/debounce");
const isEmpty = require("lodash/isEmpty");

But! You'll have an overall smaller import size... however, the package size is larger! So to mitigate this, they broke up some of the popular methods into their own separate packages: lodash.get, lodash.debounce, and lodash.isEmpty!

So, in summation, if you don't plan on utilizing CJS/UMD/AMD (like lodash does), then tree-shaking will work as expected in production when using webpack and ESM packages within the client. However, if you are including additional builds for more compatibility, then you'll have to create an array of rollup configs with different inputs and different outputs.

For example:

const resolutions = {
    globals: {
        react: "React",
        "react-is": "reactIs",
    },
    exports: "named",
};

export default [
  {
    input: "./src/index.js", // this transforms the entire source
    output: [
        {
            file: pkg.main,
            format: "cjs",
            ...resolutions,
        },
        {
            file: pkg.fallback,
            format: "umd",
            name: "My-Example-Library",
            ...resolutions,
        },
        {
            file: pkg.module,
            format: "esm",
            ...resolutions,
        },
    ],
    ...etc
  },
  {
    input: "./src/components/example.js", // this transforms just an "example.js" file and ouputs to a "dist/example.[build].js" file
    output: [
        {
            file: "dist/example.cjs.js,
            format: "cjs",
            ...resolutions,
        },
        {
            file: dist/example.umd.js,
            format: "umd",
            name: "My-Example",
            ...resolutions,
        },
    ],
    ...etc
  }
]

More info about use cases for the different builds can be found here and an example Rollup config can be found here.


问:
Undefined reference error when i try to compile on my home PC
Ok, so I've tried to get more familiar with OOP in C++ and I got the following code:

//main.cpp
#include <iostream>
#include "ZooAnimal.h"

using namespace std;

int main()
{
    ZooAnimal bozo;
    bozo.set_name(12);
    // bozo.Create("Bozo", 408, 1027, 400);

    // cout << "This animal's name is " << bozo.reptName() << endl;

    // bozo.Destroy();
    cout << "Hello";
}
```

<pre class="lang-cpp prettyprint-override"><code>//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H

class ZooAnimal
{
private:
    std::string name;
    int cageNumber;
    int weightDate;
    int weight;

public:
    void Create(std::string, int, int, int);
    void Destroy();
    std::string reptName();
    int daysSinceLastWeighted(int today);
    void set_name(int);
};

#endif //ZooAnimal
</code>```

and lastly,

//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>

void ZooAnimal::Create(std::string a, int b, int c, int d)
{
    //This creates a ZooAnimal Object
    name = a;
    cageNumber = b;
    weightDate = c;
    weight = d;
}

int ZooAnimal::daysSinceLastWeighted(int today)
{
    //calculate how many days have passed since last weight
    return today - weightDate;
}

//clear up the memory
void ZooAnimal::Destroy()
{
    delete &name;
}

// return the animal name
std::string ZooAnimal::reptName()
{
    return name;
}

void ZooAnimal::set_name(int a)
{
    cageNumber = a;
}
```

<p>So, when I try to run this code(from main.cpp of course) it won't compile and I get the following message in the console</p>

```C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status
```

I'm using MinGW to compile, working on a Windows 10 machine. The weird thing is that when I try to run the same code on a cloud editor, like repl.it , it works just fine, and if I don't separate my code into multiple files, again, it runs fine.
Any idea of what can I do?

答:
if I don't separate my code into multiple files, again, it runs fine.
  Any idea of what can I do?

Therein lies the clue to your problem. The linker can find the void ZooAnimal::set_name(int a) function in the one file. But when you separate your code into separate files you must tell the linker where it can find the definition of the function.

You can do this as follows. I'm using gcc

```<code>g++ -c file1.cpp  //compile your first source file
g++ -c file2.cpp  //and now the second
g++ -o myprog.exe file1.o file2.o //link the 2 object files to get your .exe
</code>```

As a next step you can also compile and build by using a makefile where you specify where the linker can find all the object code for the various functions you've written. Remember you may have multiple files down the road. For this exercise it might be overkill but you can read about it here.

Body:
Ok, so I've tried to get more familiar with OOP in C++ and I got the following code:

//main.cpp
#include <iostream>
#include "ZooAnimal.h"

using namespace std;

int main()
{
    ZooAnimal bozo;
    bozo.set_name(12);
    // bozo.Create("Bozo", 408, 1027, 400);

    // cout << "This animal's name is " << bozo.reptName() << endl;

    // bozo.Destroy();
    cout << "Hello";
}

//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H

class ZooAnimal
{
private:
    std::string name;
    int cageNumber;
    int weightDate;
    int weight;

public:
    void Create(std::string, int, int, int);
    void Destroy();
    std::string reptName();
    int daysSinceLastWeighted(int today);
    void set_name(int);
};

#endif //ZooAnimal

and lastly,

//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>

void ZooAnimal::Create(std::string a, int b, int c, int d)
{
    //This creates a ZooAnimal Object
    name = a;
    cageNumber = b;
    weightDate = c;
    weight = d;
}

int ZooAnimal::daysSinceLastWeighted(int today)
{
    //calculate how many days have passed since last weight
    return today - weightDate;
}

//clear up the memory
void ZooAnimal::Destroy()
{
    delete &name;
}

// return the animal name
std::string ZooAnimal::reptName()
{
    return name;
}

void ZooAnimal::set_name(int a)
{
    cageNumber = a;
}

So, when I try to run this code(from main.cpp of course) it won't compile and I get the following message in the console

C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status

I'm using MinGW to compile, working on a Windows 10 machine. The weird thing is that when I try to run the same code on a cloud editor, like repl.it , it works just fine, and if I don't separate my code into multiple files, again, it runs fine.
Any idea of what can I do?

Body:
if I don't separate my code into multiple files, again, it runs fine.
  Any idea of what can I do?

Therein lies the clue to your problem. The linker can find the void ZooAnimal::set_name(int a) function in the one file. But when you separate your code into separate files you must tell the linker where it can find the definition of the function.

You can do this as follows. I'm using gcc

g++ -c file1.cpp  //compile your first source file
g++ -c file2.cpp  //and now the second
g++ -o myprog.exe file1.o file2.o //link the 2 object files to get your .exe

As a next step you can also compile and build by using a makefile where you specify where the linker can find all the object code for the various functions you've written. Remember you may have multiple files down the road. For this exercise it might be overkill but you can read about it here.


问:
Best practice to retrieve IAM role temporary credentials
We have an external application resides outside of Amazon network and it needs to access our SQS and send message there, in order for our AWS resource to recognize the request from that application it needs to sign its request with the credentials of the IAM role we created, I'm wondering what is the best way for that external application to retrieve temp credentials from us? I have tried to implement it using Amazon Cognito but it looks like Cognito fits more in scenarios like user sign-up and sign-in with an User Interface, anyone has any suggestions? Thanks in advance.</p>

答:
To be able to obtain temporary credentials, you need a form of permanent credentials that can access (or generate) the temporary credentials.

Given your situation, you might consider creating an IAM User in your account and giving those credentials to the third-party. Grant the appropriate permissions to those credentials and they can use them directly with Amazon SQS.

Or, if you'd rather not give IAM credentials to third-parties, you could ask them to create an AWS account and an IAM User. You could then grant their IAM user access to the Amazon SQS queue.

Another option is that the third-party could access an application or API that you provide. Once they authenticate, you can provide temporary credentials created with the Security Token Service. Cognito would be an option for performing this authentication and it can also provide credentials for an associated IAM Role, thus giving them access to the Amazon SQS queue.


问:
Console hangs on newline after getting user input
I need this program to ask the user to input a number to add to an array. After they input the number, the console goes to a newline until you press another key, at which point it will do the same thing over again. I'm new to C# and I assume this has something to do with the fact that it's reading the enter key after the user inputs the information, so I need to use something equivalent to cin.ignore(), but I haven't been able to find anything that solves the issue.

```<code>public void InputSet()
{
    int userInput;

    do
    {
        C.Write("Enter an element (Enter to end): ");
        userInput = Convert.ToInt32(C.ReadLine()); // Read user input

        if (userInput < 1 || userInput > 50) // Check if in bounds
            C.WriteLine("Input is invalid. Enter from 1 to 50."); // Error message if out of bounds
        else
        {
            Array.Resize(ref arr, arr.Length + 1); // Expand array and then add it in
            arr[arr.Length - 1] = userInput;
        }
    } while(Console.ReadKey (true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop
</code>```

Here is a video of the problem:
Hanging on newline

答:
I am not entirely sure i understand your question or the problem

However,

You should probably be using a List instead of an array

You should be using int.TryParse to validate user input

You should probably be using Console.ReadLine instead of ReadKey

You can check result == string.Empty to exit

Example

```<code>var list = new List<int>();

while (true)
{
   Console.Write("Enter an element (Enter to end): ");
   var result = Console.ReadLine();

   if (result == string.Empty) break;
   if (!int.TryParse(result, out var value))
   {
      Console.WriteLine("You had one job...");
      continue;
   }
   list.Add(value);
}

Console.WriteLine(string.Join(", " , list));

Console.ReadKey();
</code>```

Output

```<code>Enter an element (Enter to end): 2
Enter an element (Enter to end): 3
Enter an element (Enter to end): 4
Enter an element (Enter to end): 6
Enter an element (Enter to end): f
You had one job...
Enter an element (Enter to end):
2, 3, 4, 6
</code>```

Body:
I need this program to ask the user to input a number to add to an array. After they input the number, the console goes to a newline until you press another key, at which point it will do the same thing over again. I'm new to C# and I assume this has something to do with the fact that it's reading the enter key after the user inputs the information, so I need to use something equivalent to cin.ignore(), but I haven't been able to find anything that solves the issue.

public void InputSet()
{
    int userInput;

    do
    {
        C.Write("Enter an element (Enter to end): ");
        userInput = Convert.ToInt32(C.ReadLine()); // Read user input

        if (userInput < 1 || userInput > 50) // Check if in bounds
            C.WriteLine("Input is invalid. Enter from 1 to 50."); // Error message if out of bounds
        else
        {
            Array.Resize(ref arr, arr.Length + 1); // Expand array and then add it in
            arr[arr.Length - 1] = userInput;
        }
    } while(Console.ReadKey (true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop

Here is a video of the problem:
Hanging on newline

Body:
I am not entirely sure i understand your question or the problem

However,

You should probably be using a List instead of an array

You should be using int.TryParse to validate user input

You should probably be using Console.ReadLine instead of ReadKey

You can check result == string.Empty to exit

Example

var list = new List<int>();

while (true)
{
   Console.Write("Enter an element (Enter to end): ");
   var result = Console.ReadLine();

   if (result == string.Empty) break;
   if (!int.TryParse(result, out var value))
   {
      Console.WriteLine("You had one job...");
      continue;
   }
   list.Add(value);
}

Console.WriteLine(string.Join(", " , list));

Console.ReadKey();

Output

Enter an element (Enter to end): 2
Enter an element (Enter to end): 3
Enter an element (Enter to end): 4
Enter an element (Enter to end): 6
Enter an element (Enter to end): f
You had one job...
Enter an element (Enter to end):
2, 3, 4, 6


问:
C++ Statement Reordering
This is a question about Chandler's answer here (I didn't have a high enough rep to comment): Enforcing statement order in C++

In his answer, suppose foo() has no input or output.  It's a black box that does work that is observable eventually, but won't be needed immediately (e.g. executes some callback).  So we don't have input/output data locally handy to tell the compiler not to optimize.  But I know that foo() will modify the memory somewhere, and the result will be observable eventually. Will the following prevent statement reordering and get the correct timing in this case?

```<code>#include <chrono>
#include <iostream>

//I believe this tells the compiler that all memory everywhere will be clobbered?
//(from his cppcon talk: https://youtu.be/nXaxk27zwlk?t=2441)
__attribute__((always_inline)) inline void DoNotOptimize() {
  asm volatile("" : : : "memory");
}

// The compiler has full knowledge of the implementation.
static int ugly_global = 1; //we print this to screen sometime later
static void foo(void) { ugly_global *= 2; }

auto time_foo() {
  using Clock = std::chrono::high_resolution_clock;

  auto t1 = Clock::now();         // Statement 1
  DoNotOptimize();
  foo();                          // Statement 2
  DoNotOptimize();
  auto t2 = Clock::now();         // Statement 3

  return t2 - t1;
}
</code>```

答:
Will the following prevent statement reordering and get the correct timing in this case?

It should not be necessary because the calls to Clock::now should, at the language-definition level, enforce enough ordering.  (That is, the C++11 standard says that the high resolution clock ought to get as much information as the system can give here, in the way that is most useful here.  See "secondary question" below.)

But there is a more general case.  It's worth thinking about the question: How does whoever provides the C++ library implementation actually write this function?  Or, take C++ itself out of the equation.  Given a language standard, how does an implementor—a person or group writing an implementation of that language—get you what you need?  Fundamentally, we need to make a distinction between what the language standard requires and how an implementation provider goes about implementing the requirements.

The language itself may be expressed in terms of an abstract machine, and the C and C++ languages are.  This abstract machine is pretty loosely defined: it executes some kind of instructions, which access data, but in many cases we don't know how it does these things, or even how big the various data items are (with some exceptions for fixed-size integers like int64_t), and os on.  The machine may or may not have "registers" that hold things in ways that cannot be addressed as well as memory that can be addressed and whose addresses can be recorded in pointers:

```<code>p = &var
</code>```

makes the value store in p (in memory or a register) such that using *p accesses the value stored in var (in memory or a register—some machines, especially back in the olden days, have / had addressable registers).1

Nonetheless, despite all of this abstraction, we want to run real code on real machines.  Real machines have real constraints: some instructions might require particular values in particular registers (think about all the bizarre stuff in the x86 instruction sets, or wide-result integer multipliers and dividers that use special-purpose registers, as on some MIPS processors), or cause CPU sychronizations, or whatever.

GCC in particular invented a system of constraints to express what you could or could not do on the machine itself, using the machine's instruction set.  Over time, this evolved into user-accessible asm constructs with input, output, and clobber sections.  The particular one you show:

```<code>__attribute__((always_inline)) inline void DoNotOptimize() {
  asm volatile("" : : : "memory");
}
</code>```

expresses the idea that "this instruction" (asm; the actual provided instruction is blank) "cannot be moved" (volatile) "and clobbers all of the computer's memory, but no registers" ("memory" as the clobber section).

This is not part of either C or C++ as a language.  It's just a compiler construction, supported by GCC and now supported by clang as well.  But it suffices to force the compiler to issue all stores-to-memory before the asm, and reload values from memory as needed after the asm, in case they changed when the computer executed the (nonexistent) instruction included in the asm line.  There's no guarantee that this will work, or even compile at all, in some other compiler, but as long as we're the implementor, we choose the compiler we're implementing for/with.

C++ as a language now has support for ordered memory operations, which an implementor must implement.  The implementor can use these asm volatile constructs to achieve the right result, provided they do actually achieve the right result.  For instance, if we need to cause the machine itself to synchronize—to emit a memory barrier—we can stick the appropriate machine instruction, such as mfence or membar #sync or whatever it may be, in the asm's instruction-section clause.  See also compiler reordering vs memory reordering as Klaus mentioned in a comment.

It is up to the implementor to find an appropriately effective trick, compiler-specific or not, to get the right semantics while minimizing any runtime slowdown: for instance, we might want to use lfence rather than mfence if that's sufficient, or membar #LoadLoad, or whatever the right thing is for the machine.  If our implementation of Clock::now requires some sort of fancy inline asm, we write one.  If not, we don't.  We make sure that we produce what's required—and then all users of the system can just use it, without needing to know what sort of grubby implementation tricks we had to invoke.

There's a secondary question here: does the language specification really constrain the implementor the way we think/hope it does?  Chris Dodd's comment says he thinks so, and he's usually right on these kinds of questions.  A couple of other commenters think otherwise, but I'm with Chris Dodd on this one.  I think it is not necessary.  You can always compile to assembly, or disassemble the compiled program, to check, though!

If the compiler didn't do the right thing, that asm would force it to do the right thing, in GCC and clang.  It probably wouldn't work in other compilers.

1On the KA-10 in particular, the registers were just the first sixteen words of memory.  As the Wikipedia page notes, this meant you could put instructions into there and call them.  Because the first 16 words were the registers, these instructions ran much faster than other instructions.

Title: C++ Statement Reordering

Body:
This is a question about Chandler's answer here (I didn't have a high enough rep to comment): Enforcing statement order in C++

In his answer, suppose foo() has no input or output.  It's a black box that does work that is observable eventually, but won't be needed immediately (e.g. executes some callback).  So we don't have input/output data locally handy to tell the compiler not to optimize.  But I know that foo() will modify the memory somewhere, and the result will be observable eventually. Will the following prevent statement reordering and get the correct timing in this case?

#include <chrono>
#include <iostream>

//I believe this tells the compiler that all memory everywhere will be clobbered?
//(from his cppcon talk: https://youtu.be/nXaxk27zwlk?t=2441)
__attribute__((always_inline)) inline void DoNotOptimize() {
  asm volatile("" : : : "memory");
}

// The compiler has full knowledge of the implementation.
static int ugly_global = 1; //we print this to screen sometime later
static void foo(void) { ugly_global *= 2; }

auto time_foo() {
  using Clock = std::chrono::high_resolution_clock;

  auto t1 = Clock::now();         // Statement 1
  DoNotOptimize();
  foo();                          // Statement 2
  DoNotOptimize();
  auto t2 = Clock::now();         // Statement 3

  return t2 - t1;
}

Body:
Will the following prevent statement reordering and get the correct timing in this case?

It should not be necessary because the calls to Clock::now should, at the language-definition level, enforce enough ordering.  (That is, the C++11 standard says that the high resolution clock ought to get as much information as the system can give here, in the way that is most useful here.  See "secondary question" below.)

But there is a more general case.  It's worth thinking about the question: How does whoever provides the C++ library implementation actually write this function?  Or, take C++ itself out of the equation.  Given a language standard, how does an implementor—a person or group writing an implementation of that language—get you what you need?  Fundamentally, we need to make a distinction between what the language standard requires and how an implementation provider goes about implementing the requirements.

The language itself may be expressed in terms of an abstract machine, and the C and C++ languages are.  This abstract machine is pretty loosely defined: it executes some kind of instructions, which access data, but in many cases we don't know how it does these things, or even how big the various data items are (with some exceptions for fixed-size integers like int64_t), and os on.  The machine may or may not have "registers" that hold things in ways that cannot be addressed as well as memory that can be addressed and whose addresses can be recorded in pointers:

p = &var

makes the value store in p (in memory or a register) such that using *p accesses the value stored in var (in memory or a register—some machines, especially back in the olden days, have / had addressable registers).1

Nonetheless, despite all of this abstraction, we want to run real code on real machines.  Real machines have real constraints: some instructions might require particular values in particular registers (think about all the bizarre stuff in the x86 instruction sets, or wide-result integer multipliers and dividers that use special-purpose registers, as on some MIPS processors), or cause CPU sychronizations, or whatever.

GCC in particular invented a system of constraints to express what you could or could not do on the machine itself, using the machine's instruction set.  Over time, this evolved into user-accessible asm constructs with input, output, and clobber sections.  The particular one you show:

__attribute__((always_inline)) inline void DoNotOptimize() {
  asm volatile("" : : : "memory");
}

expresses the idea that "this instruction" (asm; the actual provided instruction is blank) "cannot be moved" (volatile) "and clobbers all of the computer's memory, but no registers" ("memory" as the clobber section).

This is not part of either C or C++ as a language.  It's just a compiler construction, supported by GCC and now supported by clang as well.  But it suffices to force the compiler to issue all stores-to-memory before the asm, and reload values from memory as needed after the asm, in case they changed when the computer executed the (nonexistent) instruction included in the asm line.  There's no guarantee that this will work, or even compile at all, in some other compiler, but as long as we're the implementor, we choose the compiler we're implementing for/with.

C++ as a language now has support for ordered memory operations, which an implementor must implement.  The implementor can use these asm volatile constructs to achieve the right result, provided they do actually achieve the right result.  For instance, if we need to cause the machine itself to synchronize—to emit a memory barrier—we can stick the appropriate machine instruction, such as mfence or membar #sync or whatever it may be, in the asm's instruction-section clause.  See also compiler reordering vs memory reordering as Klaus mentioned in a comment.

It is up to the implementor to find an appropriately effective trick, compiler-specific or not, to get the right semantics while minimizing any runtime slowdown: for instance, we might want to use lfence rather than mfence if that's sufficient, or membar #LoadLoad, or whatever the right thing is for the machine.  If our implementation of Clock::now requires some sort of fancy inline asm, we write one.  If not, we don't.  We make sure that we produce what's required—and then all users of the system can just use it, without needing to know what sort of grubby implementation tricks we had to invoke.

There's a secondary question here: does the language specification really constrain the implementor the way we think/hope it does?  Chris Dodd's comment says he thinks so, and he's usually right on these kinds of questions.  A couple of other commenters think otherwise, but I'm with Chris Dodd on this one.  I think it is not necessary.  You can always compile to assembly, or disassemble the compiled program, to check, though!

If the compiler didn't do the right thing, that asm would force it to do the right thing, in GCC and clang.  It probably wouldn't work in other compilers.

1On the KA-10 in particular, the registers were just the first sixteen words of memory.  As the Wikipedia page notes, this meant you could put instructions into there and call them.  Because the first 16 words were the registers, these instructions ran much faster than other instructions.


问:
Return rows in pandas based on values in multiple columns
Needed some help with pandas...I'm working on this data and I'm trying to calculate some changes over time per region.
Basically, I'm trying to find the oldest quantity and the newest quantity for each area in question. I have code that can give me the year of the most recent and oldest data recordes, however I need to gather the whole row so I can work on the 'quantity' column. Any inputs? here is what i have :

df.groupby(['Country or Area'])['Year'].max()

Thanks in advance!

答:
Use idxmin() and idxmax().  Something like:</p>

```<code>grp = df.groupby(['Country or Area'])

for name,group in grp:
    print(name)

    minidx = group['Year'].idxmin()
    maxidx = group['Year'].idxmax()

    print(f"min: {group['Year'][minidx]} {group['Quantity'][minidx]}")
    print(f"max: {group['Year'][maxidx]} {group['Quantity'][maxidx]}")
    print()
</code>```

Body:
Use idxmin() and idxmax().  Something like:

grp = df.groupby(['Country or Area'])

for name,group in grp:
    print(name)

    minidx = group['Year'].idxmin()
    maxidx = group['Year'].idxmax()

    print(f"min: {group['Year'][minidx]} {group['Quantity'][minidx]}")
    print(f"max: {group['Year'][maxidx]} {group['Quantity'][maxidx]}")
    print()


问:
Create new variable using a lookup table
I want to create a new variable using a lookup table. The dataframe looks like this:

```<code>  id    sex     age length
   1    Female  1   45
   2    Female  2   54
   3    Female  3   56
   4    Female  4   60
   5    Female  5   60
   6    Female  6   61
   7    Female  7   63
   8    Male    1   55
   9    Male    2   54
   10   Male    3   58
   11   Male    4   61
   12   Male    5   65
   13   Male    6   63
   14   Male    7   65
   15   Male    8   67
   16   Male    9   68
   17   Male    10  69
</code>```

and the lookup table looks like this

```<code>sex    age  length
Female  1   50
Female  2   53
Female  3   56
Female  4   58
Female  5   60
Female  6   61
Female  7   63
Male    1   50
Male    2   54
Male    3   57
Male    4   60
Male    5   62
Male    6   63
Male    7   65
Male    8   66
Male    9   67
Male    10  69
</code>```

I want to create a new variable growth.rate with two levels: "Normal" and "Low", so the final data frame looks like this ,

```<code>id   sex   age  length  growth.rate
1   Female  1   45  Low
2   Female  2   54  Normal
3   Female  3   56  Low
4   Female  4   60  Normal
5   Female  5   60  Low
6   Female  6   61  Low
7   Female  7   63  Low
8   Male    1   55  Normal
9   Male    2   54  Low
10  Male    3   58  Normal
11  Male    4   61  Normal
12  Male    5   65  Normal
13  Male    6   63  Low
14  Male    7   65  Low
15  Male    8   67  Normal
16  Male    9   68  Normal
17  Male    10  69  Low
</code>```

In this example, the growth.rate for id 1 is "Low" because her length is lower than the value in the lookup table for females age 1.

Conversely, the growth.rate for id 2 is "Normal" because her length is higher than the value in the lookup table for females age 2.

I tried to adapt this solution without success  Getting contextstack overflow error - too many nested ifelse statements within for loop?

any help is much appreciated

答:
If we do a left_join betweeen the first and lookup dataset based on 'sex', 'age, we get two 'length' column, do the comparison   between those columns and create a new column with ifelse or case_when

```<code>library(dplyr)
left_join(df1, lookup, by = c('sex', 'age')) %>%
    transmute(id, sex, age,
      growth.rate = case_when(length.x <= length.y ~ "Low",
        TRUE ~ "Normal"), length = length.x)
#   id    sex age growth.rate length
#1   1 Female   1         Low     45
#2   2 Female   2      Normal     54
#3   3 Female   3         Low     56
#4   4 Female   4      Normal     60
#5   5 Female   5         Low     60
#6   6 Female   6         Low     61
#7   7 Female   7         Low     63
#8   8   Male   1      Normal     55
#9   9   Male   2         Low     54
#10 10   Male   3      Normal     58
#11 11   Male   4      Normal     61
#12 12   Male   5      Normal     65
#13 13   Male   6         Low     63
#14 14   Male   7         Low     65
#15 15   Male   8      Normal     67
#16 16   Male   9      Normal     68
#17 17   Male  10         Low     69
</code>```

In data.table, this can be made more compact

```<code>library(data.table)
setDT(df1)[lookup, growth.rate := fcase(length <= i.length, "Low",
           "Normal"), on = .(sex, age)]
</code>```

Or with an index

```<code>setDT(df1)[lookup, growth.rate :=
       c("Normal", "Low")[1 + (length <= i.length)], on = .(sex, age)]
</code>```

data

```<code>df1 <- structure(list(id = 1:17, sex = c("Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male"), age = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L
), length = c(45L, 54L, 56L, 60L, 60L, 61L, 63L, 55L, 54L, 58L,
61L, 65L, 63L, 65L, 67L, 68L, 69L)), class = "data.frame", row.names = c(NA,
-17L))

lookup <- structure(list(sex = c("Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male"), age = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L
), length = c(50L, 53L, 56L, 58L, 60L, 61L, 63L, 50L, 54L, 57L,
60L, 62L, 63L, 65L, 66L, 67L, 69L)), class = "data.frame", row.names = c(NA,
-17L))
</code>```

Body:
I want to create a new variable using a lookup table. The dataframe looks like this:

  id    sex     age length
   1    Female  1   45
   2    Female  2   54
   3    Female  3   56
   4    Female  4   60
   5    Female  5   60
   6    Female  6   61
   7    Female  7   63
   8    Male    1   55
   9    Male    2   54
   10   Male    3   58
   11   Male    4   61
   12   Male    5   65
   13   Male    6   63
   14   Male    7   65
   15   Male    8   67
   16   Male    9   68
   17   Male    10  69

and the lookup table looks like this

sex    age  length
Female  1   50
Female  2   53
Female  3   56
Female  4   58
Female  5   60
Female  6   61
Female  7   63
Male    1   50
Male    2   54
Male    3   57
Male    4   60
Male    5   62
Male    6   63
Male    7   65
Male    8   66
Male    9   67
Male    10  69

I want to create a new variable growth.rate with two levels: "Normal" and "Low", so the final data frame looks like this ,

id   sex   age  length  growth.rate
1   Female  1   45  Low
2   Female  2   54  Normal
3   Female  3   56  Low
4   Female  4   60  Normal
5   Female  5   60  Low
6   Female  6   61  Low
7   Female  7   63  Low
8   Male    1   55  Normal
9   Male    2   54  Low
10  Male    3   58  Normal
11  Male    4   61  Normal
12  Male    5   65  Normal
13  Male    6   63  Low
14  Male    7   65  Low
15  Male    8   67  Normal
16  Male    9   68  Normal
17  Male    10  69  Low

In this example, the growth.rate for id 1 is "Low" because her length is lower than the value in the lookup table for females age 1.

Conversely, the growth.rate for id 2 is "Normal" because her length is higher than the value in the lookup table for females age 2.

I tried to adapt this solution without success  Getting contextstack overflow error - too many nested ifelse statements within for loop?

any help is much appreciated

Body:
If we do a left_join betweeen the first and lookup dataset based on 'sex', 'age, we get two 'length' column, do the comparison   between those columns and create a new column with ifelse or case_when

library(dplyr)
left_join(df1, lookup, by = c('sex', 'age')) %>%
    transmute(id, sex, age,
      growth.rate = case_when(length.x <= length.y ~ "Low",
        TRUE ~ "Normal"), length = length.x)
#   id    sex age growth.rate length
#1   1 Female   1         Low     45
#2   2 Female   2      Normal     54
#3   3 Female   3         Low     56
#4   4 Female   4      Normal     60
#5   5 Female   5         Low     60
#6   6 Female   6         Low     61
#7   7 Female   7         Low     63
#8   8   Male   1      Normal     55
#9   9   Male   2         Low     54
#10 10   Male   3      Normal     58
#11 11   Male   4      Normal     61
#12 12   Male   5      Normal     65
#13 13   Male   6         Low     63
#14 14   Male   7         Low     65
#15 15   Male   8      Normal     67
#16 16   Male   9      Normal     68
#17 17   Male  10         Low     69

In data.table, this can be made more compact

library(data.table)
setDT(df1)[lookup, growth.rate := fcase(length <= i.length, "Low",
           "Normal"), on = .(sex, age)]

Or with an index

setDT(df1)[lookup, growth.rate :=
       c("Normal", "Low")[1 + (length <= i.length)], on = .(sex, age)]

data

df1 <- structure(list(id = 1:17, sex = c("Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male"), age = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L
), length = c(45L, 54L, 56L, 60L, 60L, 61L, 63L, 55L, 54L, 58L,
61L, 65L, 63L, 65L, 67L, 68L, 69L)), class = "data.frame", row.names = c(NA,
-17L))

lookup <- structure(list(sex = c("Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male"), age = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L
), length = c(50L, 53L, 56L, 58L, 60L, 61L, 63L, 50L, 54L, 57L,
60L, 62L, 63L, 65L, 66L, 67L, 69L)), class = "data.frame", row.names = c(NA,
-17L))


问:
Shared Lambda authorizer setup in Serverless Framework
I am trying to create a custom Lambda authorizer that will be shared between a few different services/serverless stacks. If I understand the documentation here https://serverless.com/framework/docs/providers/aws/events/apigateway/#note-while-using-authorizers-with-shared-api-gateway, that means that I need to create a shared authorizer resource in a “common resources” service/serverless stack, and then refer to that shared authorizer from my other services. First of all: Is my understanding correct?

If my understanding is correct, my next question becomes: How do I do this? The documentation doesn’t provide a clear example for lambda authorizers, so here’s how I tried to customize it:

```<code>functions:
authorizerFunc:
handler: authorizer/authorizer.handler
runtime: nodejs8.10

resources:
Resources:
authorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
AuthorizerResultTtlInSeconds: 0
Name: Authorizer
Type: REQUEST
AuthorizerUri: ???
RestApiId:
Fn::ImportValue: myRestApiId
</code>```

I don’t understand what the syntax for AuthorizerUri is supposed to be. I’ve tried “Ref: authorizerFunc”, “Fn::GetAtt: [authorizerFunc, Arn]” etc. to no avail.

When I get the authorizerUri working, do I just add an Output for my authorizer resource, then Fn::ImportValue it from the services containing my API Lambdas?

Link to my question on the Serverless forum for posterity: https://forum.serverless.com/t/shared-lambda-authorizer/6447

答:
Changing to a shared custom API Gateway Lambda Authorizer was straightforward once it was working as part of the service. At that point it was just add an arn: to a deployed lambda (authorizer) and remove the "authorizer" definition from the service to a separate deployable service.

```<code>  myLambdaName:
    handler: handler.someNodeFunction
    name: something-someNodeFunction
    events:
      - http:
          path: /path/to/resource
          method: get
          cors: true
          authorizer:
            name: myCustomAuthorizer
            # forwarding lambda proxy event stuff to the custom authorizer
            IdentitySource: method.request.header.Authorization, context.path
            type: request
            arn:  'arn:aws:lambda:region:##:function:something-else-myCustomAuthorizer'
</code>```

Then the other "service" just has some custom authorizers shared by multiple deployed microservices.

```<code>functions:

  myCustomAuthorizer:
    name: something-else-myCustomAuthorizer
    handler: handler.myCustomAuthorizer
</code>```

Side note:

If you'd want a token type authorizer, which does forward the "authorization: bearer xyzsddfsf" as a simple event:

```<code>{
    "type": "TOKEN",
    "methodArn": "arn:aws:execute-api:region:####:apigwIdHere/dev/GET/path/to/resource",
    "authorizationToken": "Bearer ...."
}
</code>```

```<code>          authorizer:
            arn:  'arn:aws:lambda:region:##:function:something-else-myCustomAuthorizer'
</code>```

Body:
I am trying to create a custom Lambda authorizer that will be shared between a few different services/serverless stacks. If I understand the documentation here https://serverless.com/framework/docs/providers/aws/events/apigateway/#note-while-using-authorizers-with-shared-api-gateway, that means that I need to create a shared authorizer resource in a “common resources” service/serverless stack, and then refer to that shared authorizer from my other services. First of all: Is my understanding correct?

If my understanding is correct, my next question becomes: How do I do this? The documentation doesn’t provide a clear example for lambda authorizers, so here’s how I tried to customize it:

functions:
authorizerFunc:
handler: authorizer/authorizer.handler
runtime: nodejs8.10

resources:
Resources:
authorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
AuthorizerResultTtlInSeconds: 0
Name: Authorizer
Type: REQUEST
AuthorizerUri: ???
RestApiId:
Fn::ImportValue: myRestApiId

I don’t understand what the syntax for AuthorizerUri is supposed to be. I’ve tried “Ref: authorizerFunc”, “Fn::GetAtt: [authorizerFunc, Arn]” etc. to no avail.

When I get the authorizerUri working, do I just add an Output for my authorizer resource, then Fn::ImportValue it from the services containing my API Lambdas?

Link to my question on the Serverless forum for posterity: https://forum.serverless.com/t/shared-lambda-authorizer/6447

Body:
Changing to a shared custom API Gateway Lambda Authorizer was straightforward once it was working as part of the service. At that point it was just add an arn: to a deployed lambda (authorizer) and remove the "authorizer" definition from the service to a separate deployable service.

  myLambdaName:
    handler: handler.someNodeFunction
    name: something-someNodeFunction
    events:
      - http:
          path: /path/to/resource
          method: get
          cors: true
          authorizer:
            name: myCustomAuthorizer
            # forwarding lambda proxy event stuff to the custom authorizer
            IdentitySource: method.request.header.Authorization, context.path
            type: request
            arn:  'arn:aws:lambda:region:##:function:something-else-myCustomAuthorizer'

Then the other "service" just has some custom authorizers shared by multiple deployed microservices.

functions:

  myCustomAuthorizer:
    name: something-else-myCustomAuthorizer
    handler: handler.myCustomAuthorizer

Side note:

If you'd want a token type authorizer, which does forward the "authorization: bearer xyzsddfsf" as a simple event:

{
    "type": "TOKEN",
    "methodArn": "arn:aws:execute-api:region:####:apigwIdHere/dev/GET/path/to/resource",
    "authorizationToken": "Bearer ...."
}

          authorizer:
            arn:  'arn:aws:lambda:region:##:function:something-else-myCustomAuthorizer'