问:
React Native computational heavy task
Very simple and common use case, but I can't find satisfying answer.
I have react native app which needs to store some data locally. I am using redux and redux-observables and Realm as a storage.

What I need is: some action occur, let's say ADD_ITEM. I need to update UI with some payload (standard redux). Then I want to create/transform that payload to another piece of data and save that data into Realm (asynchronously). Whatever I try, it always lags UI (a lot).

I tried to wrap that realm call into promise and use switchMap, but it's still slow.

I haven't took a look at workers yet but they only accept strings, which is let's say much less usable for me.

I can offload completely that computation to native background thread but that will be very uncomfortable and a lot of writing.

Could async await help me? Of redux-saga? I feel like it's the same thing, not real async processing.

Or am I using completely wrong libraries for this?

```<code>const insertOrderItem = (action$) =>
    action$.ofType(Action.ADD_ORDER_ITEM)
        .switchMap(({ payload }) => Rx.Observable.fromPromise(
            new Promise((resolve, reject) => {
                storage.insert(createObject(payload)
                resolve({
                    type: "OPERATION_ADDED"
                })
            })
        ))
</code>```

In general, storing small piece of data to realm shouldn't be THAT much computational heavy but I feel like it's necessary to do this kind of jobs on background thread.

Am I missing something?

Thanks

答:
I had same problem with my app using React Native + Realm DB. I tried all ways without having to write native code and make the bridge from react-native to native, and finally I found a solution:

https://corbt.com/posts/2015/12/22/breaking-up-heavy-processing-in-react-native.html

Install npm install next-frame --save.

Add next-frame to your code import nextFrame from 'next-frame';

Add this line within a for that took long, or a for which insert in DB await nextFrame();

A complete example would look like this:

```<code>import nextFrame from 'next-frame';

let response = await fetch("https://emberall.com/user/1/recordings");
let responseJSON = await response.json();

for (let recording of responseJSON.recordings) {
  await nextFrame(); // The javascript will yield here and not resume execution until the next frame.
  mergeRecordingToLocalDatabase(recording);
}
</code>```

Basically what this does is that in every iteration or db-insert it waits for JS to render and process next UI frame, so your app will not get stuck or freeze.

P.D.: I know months have passed since question but I think a lot o people could benefit from this.

Title: React Native computational heavy task

Body:
Very simple and common use case, but I can't find satisfying answer.
I have react native app which needs to store some data locally. I am using redux and redux-observables and Realm as a storage.

What I need is: some action occur, let's say ADD_ITEM. I need to update UI with some payload (standard redux). Then I want to create/transform that payload to another piece of data and save that data into Realm (asynchronously). Whatever I try, it always lags UI (a lot).

I tried to wrap that realm call into promise and use switchMap, but it's still slow.

I haven't took a look at workers yet but they only accept strings, which is let's say much less usable for me.

I can offload completely that computation to native background thread but that will be very uncomfortable and a lot of writing.

Could async await help me? Of redux-saga? I feel like it's the same thing, not real async processing.

Or am I using completely wrong libraries for this?

const insertOrderItem = (action$) =>
    action$.ofType(Action.ADD_ORDER_ITEM)
        .switchMap(({ payload }) => Rx.Observable.fromPromise(
            new Promise((resolve, reject) => {
                storage.insert(createObject(payload)
                resolve({
                    type: "OPERATION_ADDED"
                })
            })
        ))

In general, storing small piece of data to realm shouldn't be THAT much computational heavy but I feel like it's necessary to do this kind of jobs on background thread.

Am I missing something?

Thanks

Body:
I had same problem with my app using React Native + Realm DB. I tried all ways without having to write native code and make the bridge from react-native to native, and finally I found a solution:

https://corbt.com/posts/2015/12/22/breaking-up-heavy-processing-in-react-native.html

Install npm install next-frame --save.

Add next-frame to your code import nextFrame from 'next-frame';

Add this line within a for that took long, or a for which insert in DB await nextFrame();

A complete example would look like this:

import nextFrame from 'next-frame';

let response = await fetch("https://emberall.com/user/1/recordings");
let responseJSON = await response.json();

for (let recording of responseJSON.recordings) {
  await nextFrame(); // The javascript will yield here and not resume execution until the next frame.
  mergeRecordingToLocalDatabase(recording);
}

Basically what this does is that in every iteration or db-insert it waits for JS to render and process next UI frame, so your app will not get stuck or freeze.

P.D.: I know months have passed since question but I think a lot o people could benefit from this.


来源: stackexchange

问:
C# WPF Gridview will not show data Unless clicked
I am learning WPF/C# and trying to develop a small application that lists the file names in a datagrid (Windows 10, .Net frame 4.5)
So far the code is below

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for ProcessFiles.xaml
    /// </summary>
    public partial class ProcessFiles : Window
    {
        List<FileInfo> myFileList = new List<FileInfo>();

        public ProcessFiles()
        {
            InitializeComponent();
            dGrid.AutoGenerateColumns = true;
            dGrid.UpdateLayout();
        }

        private void pButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Factory.StartNew(() => ListMyFiles(myFileList));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " +ex.Message);
            }
            finally
            {
                MessageBox.Show("Done.");
            }

            dGrid.ItemsSource = myFileList;
        }

        private void ListMyFiles(List<FileInfo> mylist)
        {
            //throw new NotImplementedException();

            foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
            {
                // var currentFile = f;
                System.Threading.Thread.Sleep(10);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.ReadyItem.Content = "Updating..." + f.FullName;
                    mylist.Add(f);
                }), DispatcherPriority.Background);
            }

        }
    }
}
</code>```

I am facing a dilemma with automatically refreshing the datagrid once after the Dispatcher task completes. If I don't activate the GUI thread with a MessageBox.Show() somewhere in the button clicked event, the GridView doesn't show any data, however, maximizing the main window, adding a MessageBox show etc start displaying the columns filled.

What I must be missing?

答:
Just change the List<T> to ObservableCollection<T> to inform the ItemsSource about changes. WPF Controls generally listen to INotifyPropertyChanged or INotifyCollectionChanged events:

ObservableCollection<FileInfo> myFileList = new ObservableCollection<FileInfo>();.

ContentLicense: CC BY-SA 3.0

Body:
I am learning WPF/C# and trying to develop a small application that lists the file names in a datagrid (Windows 10, .Net frame 4.5)
So far the code is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO;

namespace WpfApplication1
{
    ///
    /// Interaction logic for ProcessFiles.xaml
    ///
    public partial class ProcessFiles : Window
    {
        List<FileInfo> myFileList = new List<FileInfo>();

        public ProcessFiles()
        {
            InitializeComponent();
            dGrid.AutoGenerateColumns = true;
            dGrid.UpdateLayout();
        }

        private void pButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Factory.StartNew(() => ListMyFiles(myFileList));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " +ex.Message);
            }
            finally
            {
                MessageBox.Show("Done.");
            }

            dGrid.ItemsSource = myFileList;
        }

        private void ListMyFiles(List<FileInfo> mylist)
        {
            //throw new NotImplementedException();

            foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
            {
                // var currentFile = f;
                System.Threading.Thread.Sleep(10);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.ReadyItem.Content = "Updating..." + f.FullName;
                    mylist.Add(f);
                }), DispatcherPriority.Background);
            }

        }
    }
}

I am facing a dilemma with automatically refreshing the datagrid once after the Dispatcher task completes. If I don't activate the GUI thread with a MessageBox.Show() somewhere in the button clicked event, the GridView doesn't show any data, however, maximizing the main window, adding a MessageBox show etc start displaying the columns filled.

What I must be missing?


问:
How to store prices in MongoDB for best practices?
First thanks in advance for the help.

I have an application with Spring Boot and mongo using Spring Data and I have something like this:

```<code>@Document("products")
class Product {
    @Id
    private String $id;
    private String $name;
    private Money price;
    private Money deliveryPrice;
}

class Money {
    private BigDecimal amount;
    private Currency currency;
}
</code>```

If I save a product it saves like:

```<code>{
    _id: ObjectId("AAAA"),
    name: "Product 1",
    price: {
        amount: "100",
        currency: "EUR"
    },
    deliveryPrice: {
        amount: "10",
        currency: "EUR"
    }
}
</code>```

It's correct but I don't like how it saves.

I would like to store like:

```<code>{
    _id: ObjectId("AAAA"),
    name: "Product 1",
    price: DecimalNumber(100),
    deliveryPrice: DecimalNumber(10),
    currency: "EUR"
}
</code>```

That way I am not duplicating information that is not needed in all the prices value.

How can I solve this?
Is this the best solution? In case not how should it be?

Thanks

答:
```<code>class Money {
    private BigDecimal amount;
    @Transient
    private Currency currency;
}
</code>```

Now the currency property will not be persisted in MongoDB.

Body:
First thanks in advance for the help.

I have an application with Spring Boot and mongo using Spring Data and I have something like this:

@Document("products")
class Product {
    @Id
    private String $id;
    private String $name;
    private Money price;
    private Money deliveryPrice;
}

class Money {
    private BigDecimal amount;
    private Currency currency;
}

If I save a product it saves like:

{
    _id: ObjectId("AAAA"),
    name: "Product 1",
    price: {
        amount: "100",
        currency: "EUR"
    },
    deliveryPrice: {
        amount: "10",
        currency: "EUR"
    }
}

It's correct but I don't like how it saves.

I would like to store like:

{
    _id: ObjectId("AAAA"),
    name: "Product 1",
    price: DecimalNumber(100),
    deliveryPrice: DecimalNumber(10),
    currency: "EUR"
}

That way I am not duplicating information that is not needed in all the prices value.

How can I solve this?
Is this the best solution? In case not how should it be?

Thanks

Body:
class Money {
    private BigDecimal amount;
    @Transient
    private Currency currency;
}

Now the currency property will not be persisted in MongoDB.


问:
Completion block never called in setCollectionViewLayout
I'm updating the layout of a UICollectionView by moving a cell.

```<code>collectionView.moveItem(at: sourceIndex, to: destIndex)

collectionView.collectionViewLayout.invalidateLayout()

collectionView.setCollectionViewLayout(collectionView.collectionViewLayout, animated: true)
{ (done) in
      print("i'm here")
}
</code>```

But the completion block of setCollectionViewLayout is never called, while the animation is correctly done.
Any idea ?

Thank you

答:
Edit:

BallpointBen is correct - the structure change is not needed.

I believe the reason you do not get the completion block is because you are setting the New layout to the Existing layout. So, because there is no actual change, there is no "completion".

<s>Whoops... The structure should probably be:

```<code>    collectionView.setCollectionViewLayout(collectionView.collectionViewLayout,
        animated: true, completion: {
            (done) in
            print("I'm here")
    })
</code>```

</s>

Body:
I'm updating the layout of a UICollectionView by moving a cell.

collectionView.moveItem(at: sourceIndex, to: destIndex)

collectionView.collectionViewLayout.invalidateLayout()

collectionView.setCollectionViewLayout(collectionView.collectionViewLayout, animated: true)
{ (done) in
      print("i'm here")
}

But the completion block of setCollectionViewLayout is never called, while the animation is correctly done.
Any idea ?

Thank you

Body:
Edit:

BallpointBen is correct - the structure change is not needed.

I believe the reason you do not get the completion block is because you are setting the New layout to the Existing layout. So, because there is no actual change, there is no "completion".

<s>Whoops... The structure should probably be:

    collectionView.setCollectionViewLayout(collectionView.collectionViewLayout,
        animated: true, completion: {
            (done) in
            print("I'm here")
    })

</s>


问:
How to change image's href with Javascript by using title name?
Here in this slideshow there are around 50 images. I use a platform which is similar to wordpress and doesnt let me to change image href. The images have the same class name. Is it possible to use title name(which is unique for each image) and change some image's href?</p>

```<code><div id="slideshow" class="vlt-d-slider" style="position: relative; overflow: hidden; width: 928px; height: 522px;">
    <div class="slide" data-vltcaption="0" data-brand="none" data-topic="INST" data-url="_0.jpg" style="position: absolute; left: 0px; visibility: visible; z-index: 3; line-height: 520px; height: 522px;">
<a class="slide-lightbox" rel="vlt-slideshow" href="m_0.jpg" title="Pfusc number photo 1" target="_blank">
<img class="slide-img" src="_0.jpg" alt="Pfusc number photo 1">
</a>
</div>
      <div class="slide" data-vltcaption="1" data-brand="none" data-topic="INST" data-url="0.jpg" style="position: absolute; left: 0px; visibility: hidden; z-index: 1; line-height: 520px; display: block; height: 522px;">
<a class="slide-lightbox" rel="vlt-slideshow" href="f_0.jpg" title="Pfusc number photo 2" target="_blank">
<img class="slide-img" src="0.jpg" alt="Pfusc number photo 2">
</a>
</div>
      <div class="slide" ....
</div>
    </div>
</code>```

答:
For start I'm not sure do you want to change your a tag or img tag properties, but I will presume it's a tag because of you mentioned href. Yes it is. You can do it like this:

```<code>$("a[title='yourTitle']").attr('href', 'https://www.google.com/');
</code>```

and if you want image:

```<code>$('img[alt="Your Alt"]').attr('src', 'image.jpg');
</code>```

Body:
Here in this slideshow there are around 50 images. I use a platform which is similar to wordpress and doesnt let me to change image href. The images have the same class name. Is it possible to use title name(which is unique for each image) and change some image's href?

      <div class="slide" ....

Body:
For start I'm not sure do you want to change your a tag or img tag properties, but I will presume it's a tag because of you mentioned href. Yes it is. You can do it like this:

$("a[title='yourTitle']").attr('href', 'https://www.google.com/');

and if you want image:

$('img[alt="Your Alt"]').attr('src', 'image.jpg');


问:
Cython's calculations are incorrect
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

```<code>from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)
</code>```

The Cython version:

```<code>cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)
</code>```

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?

答: You are using float in the Cython version -- that's single precision!  Use double instead, which corresponds to Python's float (funnily enough).  The C type float only has about 8 significant decimal digits, whereas double or Python's float have about 16 digits.

ContentLicense: CC BY-SA 2.5

Title: Cython's calculations are incorrect

Body:
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)

The Cython version:

cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?


问:
GWT Basic Architecture
I am new to client-server application development (only experience with Java desktop).

My query is this: I have followed an excellent GWT tutorial on YouTube and understand basic OO principles being applied to client and server services and implementations. However, what if a class isn't a service - say a data class like Person storing basic information that will be used by the service classes. Where should I store these separate classes?

To give you an insight in to my current structure (using Client package hierarchy).

I have: com.me.example.client - then client.GUI & client.service packages contained here.

答:
You can choose between

Just setting these in client.

Create an extra package besides client and server : shared

When choosing for a seperate shared package you must add the following line to your gwt.xml

```<code><source path='shared'/>
</code>```

Extra info : these classes are needed at the client side, and thus need to be compiled to javascript by the gwt compiler. When putting them in client this is already the case (because client is already configured in .gwt.xml). When putting them in shared, you must tell so to the gwt compiler.

Title: GWT Basic Architecture

Body:
You can choose between

Just setting these in client.

Create an extra package besides client and server : shared

When choosing for a seperate shared package you must add the following line to your gwt.xml

<source path='shared'/>

Extra info : these classes are needed at the client side, and thus need to be compiled to javascript by the gwt compiler. When putting them in client this is already the case (because client is already configured in .gwt.xml). When putting them in shared, you must tell so to the gwt compiler.


问:
Render child route only after parent route rendered
I have a routing structure

```<code>  path: '',
    component: MainComponent,
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }
</code>```

In Main component ngOnInit I get submodules list

```<code>getSubmodules(id) {
    this.universityAsideService.getSubmodules(id)
      .subscribe((subModules) => {
        this.subModules = subModules;
      this.saveSubModules(subModules).subscribe((data) => this.goToModule(id));
        console.log('submodules in getSubmodules, UniversityAside Co');
        console.log(this.subModules);
      });
  }

  saveSubModules(subModules): Observable<any> {
    return Observable.create((obs) => {
      obs.next(localStorage.setItem('subModules', JSON.stringify({
        subModules: subModules
      })));
    });
  }
</code>```

Then Emloyees component get submodules list from localstorage and then renders view. Bu the problem when visiting localhost:4200/#/employees/ Then employees component tries to get submodules from localstorage before MainComponent save into localstorage. How can I solve this problem ? Thanks.

答:
Implement the AuthGuard to prevent the rendering of child component before parent component.

Modify the routes like:

```<code>  path: '',
    component: MainComponent,
    canActivate: [AuthGuard],
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }
</code>```

Body:
I have a routing structure

  path: '',
    component: MainComponent,
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }

In Main component ngOnInit I get submodules list

getSubmodules(id) {
    this.universityAsideService.getSubmodules(id)
      .subscribe((subModules) => {
        this.subModules = subModules;
      this.saveSubModules(subModules).subscribe((data) => this.goToModule(id));
        console.log('submodules in getSubmodules, UniversityAside Co');
        console.log(this.subModules);
      });
  }

  saveSubModules(subModules): Observable<any> {
    return Observable.create((obs) => {
      obs.next(localStorage.setItem('subModules', JSON.stringify({
        subModules: subModules
      })));
    });
  }

Then Emloyees component get submodules list from localstorage and then renders view. Bu the problem when visiting localhost:4200/#/employees/ Then employees component tries to get submodules from localstorage before MainComponent save into localstorage. How can I solve this problem ? Thanks.

Body:
Implement the AuthGuard to prevent the rendering of child component before parent component.

Modify the routes like:

  path: '',
    component: MainComponent,
    canActivate: [AuthGuard],
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }


问:
stripe not able to add bank account in test mode
I have created stripe account, which is in test mode, I want to do payout functionality, so i want to add bank account in it, but when i add bank account, It always says me Known test bank accounts cannot be used in live mode., I am using Account Number  : 000123456789 and Rounting Number :  110000000 , why i am getting this message ?  can anyone please help me ?

I did some googling but it doesn't help me. Can anyone please help me how can i resolve this issue ?

答:
You are likely using Standard accounts and trying to provide a test bank account in the OAuth form.

Even if you're in test mode, it is not possible to provide fake information in the OAuth form, as the account that would be created is a real account that might be used in live mode later. Instead, if you're using your platform's development client_id, you should use the "Skip this form" link at the top of the OAuth form.

Unfortunately, that means it is not possible to test payouts with Standard accounts without providing real bank account information. In practice though, there's little need to test this feature: with Standard accounts, the platform does not have control over payouts, and the account's owner will directly set their payout settings in their dashboard.


问:
how to split rows of a dataframe in multiple rows based on start date and end date?
I've got a dataset with a starting date and an enddate, and I want to split the rows in this dataframe based on the year in the period. Take this data frame for example:

```<code>df <- data.frame("starting_date"=as.Date("2015-06-01"),"end_date"=as.Date("2017-09-30"))
</code>```

It should be split into 3 rows, one with starting date 2015-06-01 and end date 2015-12-31, one with starting date 2016-01-01 and end date 2016-12-31, and one with starting date 2017-01-01 and end date 2017-09-30. Any idea how to do this? It should look like this in the end:

```<code>  starting_date   end_date
1    2015-06-01 2015-12-31
2    2016-01-01 2016-12-31
3    2017-01-01 2017-09-30
</code>```

EDIT: I have adjusted the code to work in base R.

EDIT2: I tried

```<code>library(dplyr)
df2 <- df[1,]
df2 <- df[-1,]
for (i in 1:dim(df)[1]){
  for (j in year(df$starting_date[i]):year(df$end_date[i]))
  {
    df2 <- bind_rows(df2,df[i,])
  }
}
</code>```

It works, but it is impossibly slow.

EDIT3:
I managed to replicate the lines equal to the number of years involved:

```<code>df2 <- df[rep(seq_len(nrow(df)),year(df$end_date)-year(df$starting_date)+1),]
</code>```

Now I would need another column with the years like this:

```<code>  starting_date   end_date  years
1    2015-06-01 2017-09-30   2015
2    2015-06-01 2017-09-30   2016
3    2015-06-01 2017-09-30   2017
</code>```

Once I am here it is easy to get the required end result.... Any idea on how to do this?
I tried to make a seperate vector with the years, in order to cbind it with df2, but it didn't work....

```<code>years <- lapply(df,function(x) seq(x[,"starting_date"],length.out=x[,"year"]))
</code>```

EDIT4:
Finally managed to do it with the help of this post: R Create a time sequence as xts index based on two columns in data.frame
The code can probably be improved upon a lot, but it works....

```<code>diffs <- abs(with(df, year(starting_date)-year(end_date)))+1
df.rep <- df[rep(1:nrow(df), times=diffs), ]
reps <- rep(diffs, times=diffs)

dates.l <- apply(
  df[colnames(df) %in% c("starting_date", "end_date")], 1,
  function(x) {
    seq(min(year(as.Date(x))), max(year(as.Date(x))))
  })

years <- do.call(c, dates.l)
df.long <- cbind(df.rep, reps, years)
df.long$yearstart <- as.Date(paste0(year(df.long$years),"-01-01"))
df.long$yearend <- as.Date(paste0(year(df.long$years),"-12-31"))
df.long$starting_date2 <- pmax(df.long$starting_date,df.long$yearstart)
df.long$end_date2 <- pmin(df.long$end_date,df.long$yearend)
</code>```

答:
Another approach could be

```<code>library(dplyr)
library(lubridate)

#sample data
df <- data.frame("starting_date" = as.Date(c("2015-06-01", "2013-06-01", "2016-02-11")),
                 "end_date" = as.Date(c("2017-09-30", "2017-11-11", "2017-01-01")),
                 col3=c('AAA','BBB', 'CCC'),
                 col4=c('33445454','565664', '123'))

df1 <- df[,1:2] %>%
  rowwise() %>%
  do(rbind(data.frame(matrix(as.character(c(
    .$starting_date,
    seq(.$starting_date, .$end_date, by=1)[grep("\\d{4}-12-31|\\d{4}-01-01", seq(.$starting_date, .$end_date, by=1))],
    .$end_date)), ncol=2, byrow=T)))) %>%
  data.frame() %>%
  `colnames<-`(c("starting_date", "end_date")) %>%
  mutate(starting_date= as.Date(starting_date, format= "%Y-%m-%d"),
         end_date= as.Date(end_date, format= "%Y-%m-%d"))

#add temporary columns to the original and expanded date column dataframes
df$row_idx <- seq(1:nrow(df))
df$temp_col <- (year(df$end_date) - year(df$starting_date)) +1
df1 <- cbind(df1,row_idx = rep(df$row_idx,df$temp_col))

#join both dataframes to get the final result
final_df <- left_join(df1,df[,3:(ncol(df)-1)],by="row_idx") %>%
  select(-row_idx)
final_df
</code>```

Output is:

```<code>   starting_date   end_date col3     col4
1     2015-06-01 2015-12-31  AAA 33445454
2     2016-01-01 2016-12-31  AAA 33445454
3     2017-01-01 2017-09-30  AAA 33445454
4     2013-06-01 2013-12-31  BBB   565664
5     2014-01-01 2014-12-31  BBB   565664
6     2015-01-01 2015-12-31  BBB   565664
7     2016-01-01 2016-12-31  BBB   565664
8     2017-01-01 2017-11-11  BBB   565664
9     2016-02-11 2016-12-31  CCC      123
10    2017-01-01 2017-01-01  CCC      123
</code>```

Body:
I've got a dataset with a starting date and an enddate, and I want to split the rows in this dataframe based on the year in the period. Take this data frame for example:

df <- data.frame("starting_date"=as.Date("2015-06-01"),"end_date"=as.Date("2017-09-30"))

It should be split into 3 rows, one with starting date 2015-06-01 and end date 2015-12-31, one with starting date 2016-01-01 and end date 2016-12-31, and one with starting date 2017-01-01 and end date 2017-09-30. Any idea how to do this? It should look like this in the end:

  starting_date   end_date
1    2015-06-01 2015-12-31
2    2016-01-01 2016-12-31
3    2017-01-01 2017-09-30

EDIT: I have adjusted the code to work in base R.

EDIT2: I tried

library(dplyr)
df2 <- df[1,]
df2 <- df[-1,]
for (i in 1:dim(df)[1]){
  for (j in year(df$starting_date[i]):year(df$end_date[i]))
  {
    df2 <- bind_rows(df2,df[i,])
  }
}

It works, but it is impossibly slow.

EDIT3:
I managed to replicate the lines equal to the number of years involved:

df2 <- df[rep(seq_len(nrow(df)),year(df$end_date)-year(df$starting_date)+1),]

Now I would need another column with the years like this:

  starting_date   end_date  years
1    2015-06-01 2017-09-30   2015
2    2015-06-01 2017-09-30   2016
3    2015-06-01 2017-09-30   2017

Once I am here it is easy to get the required end result.... Any idea on how to do this?
I tried to make a seperate vector with the years, in order to cbind it with df2, but it didn't work....

years <- lapply(df,function(x) seq(x[,"starting_date"],length.out=x[,"year"]))

EDIT4:
Finally managed to do it with the help of this post: R Create a time sequence as xts index based on two columns in data.frame
The code can probably be improved upon a lot, but it works....

diffs <- abs(with(df, year(starting_date)-year(end_date)))+1
df.rep <- df[rep(1:nrow(df), times=diffs), ]
reps <- rep(diffs, times=diffs)

dates.l <- apply(
  df[colnames(df) %in% c("starting_date", "end_date")], 1,
  function(x) {
    seq(min(year(as.Date(x))), max(year(as.Date(x))))
  })

years <- do.call(c, dates.l)
df.long <- cbind(df.rep, reps, years)
df.long$yearstart <- as.Date(paste0(year(df.long$years),"-01-01"))
df.long$yearend <- as.Date(paste0(year(df.long$years),"-12-31"))
df.long$starting_date2 <- pmax(df.long$starting_date,df.long$yearstart)
df.long$end_date2 <- pmin(df.long$end_date,df.long$yearend)

Body:
Another approach could be

library(dplyr)
library(lubridate)

#sample data
df <- data.frame("starting_date" = as.Date(c("2015-06-01", "2013-06-01", "2016-02-11")),
                 "end_date" = as.Date(c("2017-09-30", "2017-11-11", "2017-01-01")),
                 col3=c('AAA','BBB', 'CCC'),
                 col4=c('33445454','565664', '123'))

df1 <- df[,1:2] %>%
  rowwise() %>%
  do(rbind(data.frame(matrix(as.character(c(
    .$starting_date,
    seq(.$starting_date, .$end_date, by=1)[grep("\\d{4}-12-31|\\d{4}-01-01", seq(.$starting_date, .$end_date, by=1))],
    .$end_date)), ncol=2, byrow=T)))) %>%
  data.frame() %>%
  `colnames<-`(c("starting_date", "end_date")) %>%
  mutate(starting_date= as.Date(starting_date, format= "%Y-%m-%d"),
         end_date= as.Date(end_date, format= "%Y-%m-%d"))

#add temporary columns to the original and expanded date column dataframes
df$row_idx <- seq(1:nrow(df))
df$temp_col <- (year(df$end_date) - year(df$starting_date)) +1
df1 <- cbind(df1,row_idx = rep(df$row_idx,df$temp_col))

#join both dataframes to get the final result
final_df <- left_join(df1,df[,3:(ncol(df)-1)],by="row_idx") %>%
  select(-row_idx)
final_df

Output is:

   starting_date   end_date col3     col4
1     2015-06-01 2015-12-31  AAA 33445454
2     2016-01-01 2016-12-31  AAA 33445454
3     2017-01-01 2017-09-30  AAA 33445454
4     2013-06-01 2013-12-31  BBB   565664
5     2014-01-01 2014-12-31  BBB   565664
6     2015-01-01 2015-12-31  BBB   565664
7     2016-01-01 2016-12-31  BBB   565664
8     2017-01-01 2017-11-11  BBB   565664
9     2016-02-11 2016-12-31  CCC      123
10    2017-01-01 2017-01-01  CCC      123


问:
Grid with different colours for each cell
I'm new in AngularJS (1.6) and hope you can help me with this question.

I have a grid that grows the number of columns according to the selected date range. This table always has five rows below the header.

I need to create color conditions for each cell depending on the data base value. Something like validate my data before the grid, adding a status for each data, and apply a collor condition based on this status

```<code>Ex:
    10/11   11/11   12/11   13/11
    7%      8%      3%      9%
    3%      2%      1%      4%
    9%      7%      8%      3%
    7%      8%      3%      9%
    3%      2%      1%      4%
</code>```

Controller

```<code> $scope.buscarDados = function (concessionaria, data_inicio, data_fim) {

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/GerarJsonCabecalhoGrid'
    })
    .then(function (response) {
        $scope.table_headers = response.data.table_headers;

    }, function (error) {
        console.log(error);
    });

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/buscaDadosPI'
    })
    .then(function (response) {
        $scope.items = response.data.items;
    }
)
};
</code>```

View

```<code>    <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item">{{item[table_headers[$index].name]}}</td>
            </tr>
        </tbody>
    </table>
</code>```

JSON

```<code>$scope.table_headers = [
   { "name": "id"},
   { "name": "01/08" },
   { "name": "02/08" },
   { "name": "03/08" },
   { "name": "04/08" },
   { "name": "05/08" }
];
$scope.items = [
   { "id": 1, "01/08": 10, "02/08": 13, "03/08": 22, "04/08": 26, "05/08": 33 },
   { "id": 2, "01/08": 12, "02/08": 15, "03/08": 24, "04/08": 28, "05/08": 35 },
   { "id": 3, "01/08": 14, "02/08": 17, "03/08": 26, "04/08": 30, "05/08": 37 },
   { "id": 4, "01/08": 16, "02/08": 19, "03/08": 28, "04/08": 32, "05/08": 39 },
   { "id": 5, "01/08": 18, "02/08": 21, "03/08": 30, "04/08": 35, "05/08": 41 },
   { "id": 6, "01/08": 20, "02/08": 23, "03/08": 32, "04/08": 37, "05/08": 43 }
];
</code>```

populated itens

答:
Not sure if I understood what you need. For what I have understood I think something like this may help you

```<code><div ng-controller="MyCtrl">
  <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item" ng-class="{'until-20' : item[table_headers[$index].name] <= 20, 'until-40' : item[table_headers[$index].name] > 20 && item[table_headers[$index].name] <= 40}">{{ item[table_headers[$index].name] }}</td>
            </tr>
        </tbody>
    </table>
</div>

.until-20 {
  background-color: red;
}

.until-40 {
  background-color: yellow;
}

.until-60 {
  background-color: green;
}

.until-80 {
  background-color: blue;
}

.until-100 {
  background-color: purple;
}
</code>```

Obviously you must add remaining conditions.

Otherwise you can act more massively on css, like so:

```<code><div ng-controller="MyCtrl">
  <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item" class="value-{{item[table_headers[$index].name]}}">{{ item[table_headers[$index].name] }}</td>
            </tr>
        </tbody>
    </table>
</div>

.value-0, .value-1, .value-2, .value-3, .value-4, .value-5, .value-6, .value-7, .value-8, .value-9, .value-10, .value-11, .value-12, .value-13, .value-14, .value-15, .value-16, .value-17, .value-18, .value-19, .value-20 {
  background-color: red;
}

.value-21, .value-22, .value-23, .value-24, .value-25, .value-26, .value-27, .value-28, .value-29, .value-30, .value-31, .value-32, .value-33, .value-34, .value-35, .value-36, .value-37, .value-38, .value-39, .value-40 {
  background-color: green;
}
</code>```

Hope that helps

Body:
I'm new in AngularJS (1.6) and hope you can help me with this question.

I have a grid that grows the number of columns according to the selected date range. This table always has five rows below the header.

I need to create color conditions for each cell depending on the data base value. Something like validate my data before the grid, adding a status for each data, and apply a collor condition based on this status

Ex:
    10/11   11/11   12/11   13/11
    7%      8%      3%      9%
    3%      2%      1%      4%
    9%      7%      8%      3%
    7%      8%      3%      9%
    3%      2%      1%      4%

Controller

 $scope.buscarDados = function (concessionaria, data_inicio, data_fim) {

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/GerarJsonCabecalhoGrid'
    })
    .then(function (response) {
        $scope.table_headers = response.data.table_headers;

    }, function (error) {
        console.log(error);
    });

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/buscaDadosPI'
    })
    .then(function (response) {
        $scope.items = response.data.items;
    }
)
};

View

                    {{ header.name }}

                {{item[table_headers[$index].name]}}

JSON

$scope.table_headers = [
   { "name": "id"},
   { "name": "01/08" },
   { "name": "02/08" },
   { "name": "03/08" },
   { "name": "04/08" },
   { "name": "05/08" }
];
$scope.items = [
   { "id": 1, "01/08": 10, "02/08": 13, "03/08": 22, "04/08": 26, "05/08": 33 },
   { "id": 2, "01/08": 12, "02/08": 15, "03/08": 24, "04/08": 28, "05/08": 35 },
   { "id": 3, "01/08": 14, "02/08": 17, "03/08": 26, "04/08": 30, "05/08": 37 },
   { "id": 4, "01/08": 16, "02/08": 19, "03/08": 28, "04/08": 32, "05/08": 39 },
   { "id": 5, "01/08": 18, "02/08": 21, "03/08": 30, "04/08": 35, "05/08": 41 },
   { "id": 6, "01/08": 20, "02/08": 23, "03/08": 32, "04/08": 37, "05/08": 43 }
];

populated itens

Body:
Not sure if I understood what you need. For what I have understood I think something like this may help you

<div ng-controller="MyCtrl">
  <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item" ng-class="{'until-20' : item[table_headers[$index].name] <= 20, 'until-40' : item[table_headers[$index].name] > 20 && item[table_headers[$index].name] <= 40}">{{ item[table_headers[$index].name] }}</td>
            </tr>
        </tbody>
    </table>
</div>

.until-20 {
  background-color: red;
}

.until-40 {
  background-color: yellow;
}

.until-60 {
  background-color: green;
}

.until-80 {
  background-color: blue;
}

.until-100 {
  background-color: purple;
}

Obviously you must add remaining conditions.

Otherwise you can act more massively on css, like so:

<div ng-controller="MyCtrl">
  <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item" class="value-{{item[table_headers[$index].name]}}">{{ item[table_headers[$index].name] }}</td>
            </tr>
        </tbody>
    </table>
</div>

.value-0, .value-1, .value-2, .value-3, .value-4, .value-5, .value-6, .value-7, .value-8, .value-9, .value-10, .value-11, .value-12, .value-13, .value-14, .value-15, .value-16, .value-17, .value-18, .value-19, .value-20 {
  background-color: red;
}

.value-21, .value-22, .value-23, .value-24, .value-25, .value-26, .value-27, .value-28, .value-29, .value-30, .value-31, .value-32, .value-33, .value-34, .value-35, .value-36, .value-37, .value-38, .value-39, .value-40 {
  background-color: green;
}

Hope that helps


问:
how to add multiple ports dynamically to gojs node
I am working on go.js flowchart my nodes are:

Start

Play

Que

Options

End

Start node has one output port whereas both play and que have one input and one output port,and the options node has one input port and can have one to multiple output ports at the bottom based upon user input.

Whenever User drags options node from Palette and drops it on the diagram,a popup appears which asks for user input.

So basically what I want now is to create options node's output ports based on user input.
Is there any way I can achieve this?

Below attached is the screenshot of what I have done so far and what I am trying to achieve

Here is My Code

```<code>    function show_options_opt(model,dat,node,myDiagram)
    {
     //this function is called whenever the option node is dropped to diagram div
     var portSize = new go.Size(8, 8);
    model.setDataProperty(data,'bottomArray',[]);
  $$=go.GraphObject.make;
  var portMenu =  // context menu for each port
  $$(go.Adornment, "Vertical",
    makeButton("Remove port",
               // in the click event handler, the obj.part is the Adornment;
               // its adornedObject is the port
               function (e, obj) { removePort(obj.part.adornedObject); }),
    makeButton("Change color",
               function (e, obj) { changeColor(obj.part.adornedObject); }),
    makeButton("Remove side ports",
               function (e, obj) { removeAll(obj.part.adornedObject); })
  );
   myDiagram.nodeTemplate =
  $$(go.Node, "Table",
    { locationObjectName: "BODY",
      locationSpot: go.Spot.Center,
      selectionObjectName: "BODY"
    },
     new go.Binding("location", "loc",go.Point.parse).makeTwoWay(go.Point.stringify),
  $$(go.Panel, "Horizontal",
      new go.Binding("itemArray", "bottomArray"),
      { row: 2, column: 1,
        itemTemplate:
          $$(go.Panel,
            { _side: "bottom",
              fromSpot: go.Spot.Bottom, toSpot: go.Spot.Bottom,
              fromLinkable: true, toLinkable: true, cursor: "pointer",
              contextMenu: portMenu },
            new go.Binding("portId", "portId"),
            $$(go.Shape, "Rectangle",
              { stroke: null, strokeWidth: 0,
                desiredSize: portSize,
                margin: new go.Margin(0, 1) },
              new go.Binding("fill", "portColor"))
          )  // end itemTemplate
      }
    )  // end Horizontal Panel
   );
  addPort("bottom",node,myDiagram);
   }//end function show_options_opt
</code>```

And Below Given is the addport function

```<code>   function addPort(side,node,myDiagram) {
  myDiagram.startTransaction("addPort");
  // skip any selected Links
  if (!(node instanceof go.Node)) return;
  // compute the next available index number for the side
  var i = 0;
  while (node.findPort(side + i.toString()) !== node) i++;
  // now this new port name is unique within the whole Node because of the side prefix
  var name = side + i.toString();
  // get the Array of port data to be modified
  var arr = node.data[side + "Array"];
  if (arr) {
    // create a new port data object
    var newportdata = {
      portId: name,
      portColor: go.Brush.randomColor()
      // if you add port data properties here, you should copy them in copyPortData above
    };
    // and add it to the Array of port data
    myDiagram.model.insertArrayItem(arr, -1, newportdata);
  }
    myDiagram.commitTransaction("addPort");
 }
</code>```

答: To have a variable number of objects (including in your case ports) in a node, you'll want to bind Panel.itemArray to an Array in your node data which holds one data object for each port.  This is described in Item Arrays.  There are several samples that demonstrate how to do this.  The Dynamic Ports sample might be most instructive, although you'll want to strip out a lot of the code because it has four separate Arrays of port data, each bound to four different Panels, whereas presumably you only need one Panel of ports bound to one Array of port data.

Body:
I am working on go.js flowchart my nodes are:

Start

Play

Que

Options

End

Start node has one output port whereas both play and que have one input and one output port,and the options node has one input port and can have one to multiple output ports at the bottom based upon user input.

Whenever User drags options node from Palette and drops it on the diagram,a popup appears which asks for user input.

So basically what I want now is to create options node's output ports based on user input.
Is there any way I can achieve this?

Below attached is the screenshot of what I have done so far and what I am trying to achieve

Here is My Code

    function show_options_opt(model,dat,node,myDiagram)
    {
     //this function is called whenever the option node is dropped to diagram div
     var portSize = new go.Size(8, 8);
    model.setDataProperty(data,'bottomArray',[]);
  $$=go.GraphObject.make;
  var portMenu =  // context menu for each port
  $$(go.Adornment, "Vertical",
    makeButton("Remove port",
               // in the click event handler, the obj.part is the Adornment;
               // its adornedObject is the port
               function (e, obj) { removePort(obj.part.adornedObject); }),
    makeButton("Change color",
               function (e, obj) { changeColor(obj.part.adornedObject); }),
    makeButton("Remove side ports",
               function (e, obj) { removeAll(obj.part.adornedObject); })
  );
   myDiagram.nodeTemplate =
  $$(go.Node, "Table",
    { locationObjectName: "BODY",
      locationSpot: go.Spot.Center,
      selectionObjectName: "BODY"
    },
     new go.Binding("location", "loc",go.Point.parse).makeTwoWay(go.Point.stringify),
  $$(go.Panel, "Horizontal",
      new go.Binding("itemArray", "bottomArray"),
      { row: 2, column: 1,
        itemTemplate:
          $$(go.Panel,
            { _side: "bottom",
              fromSpot: go.Spot.Bottom, toSpot: go.Spot.Bottom,
              fromLinkable: true, toLinkable: true, cursor: "pointer",
              contextMenu: portMenu },
            new go.Binding("portId", "portId"),
            $$(go.Shape, "Rectangle",
              { stroke: null, strokeWidth: 0,
                desiredSize: portSize,
                margin: new go.Margin(0, 1) },
              new go.Binding("fill", "portColor"))
          )  // end itemTemplate
      }
    )  // end Horizontal Panel
   );
  addPort("bottom",node,myDiagram);
   }//end function show_options_opt

And Below Given is the addport function

   function addPort(side,node,myDiagram) {
  myDiagram.startTransaction("addPort");
  // skip any selected Links
  if (!(node instanceof go.Node)) return;
  // compute the next available index number for the side
  var i = 0;
  while (node.findPort(side + i.toString()) !== node) i++;
  // now this new port name is unique within the whole Node because of the side prefix
  var name = side + i.toString();
  // get the Array of port data to be modified
  var arr = node.data[side + "Array"];
  if (arr) {
    // create a new port data object
    var newportdata = {
      portId: name,
      portColor: go.Brush.randomColor()
      // if you add port data properties here, you should copy them in copyPortData above
    };
    // and add it to the Array of port data
    myDiagram.model.insertArrayItem(arr, -1, newportdata);
  }
    myDiagram.commitTransaction("addPort");
 }


问:
Static AsyncTask and findViewById()
I've read a lot of questions on AsyncTask problems of different kinds, but I seem not to find the problem I'm facing.

Android Studio insists on making my custom AsyncTask static with the following note:

This AsyncTask class should be static or leaks might occur

For that reason I've been trying on using WeakReference to the Activity the task runs in. Problem is that I want to use findViewById() in onPre and onPostExecute and I cannot to access the method.
I've found that:

```<code>weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);
</code>```

does not produce an error in Android Studio, but it crashes the app.

How to solve the problem of not accessing findViewById() in the custom static AsyncTask?

Code generally works if I get rid of weakReference and make AsyncTask it non-static

Here's my AsyncTask: (the empty while loop is there on purpose so it waits until the global variable has some data.

```<code>public static class LoadingDictionaryAsync extends AsyncTask<Void, Void, Void> {

    private final WeakReference<MainScreenActivity> weakReference;

    private LoadingDictionaryAsync(MainScreenActivity mainScreenActivity){
        this.weakReference = new WeakReference<>(mainScreenActivity);
    }

    @Override
    protected void onPreExecute() {
        weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);
        weakReference.get().findViewById(R.id.dictionaryListView).setVisibility(View.GONE);
    }

    @Override
    protected Void doInBackground(Void... voids) {

        if (vocabulariesGlobal == null || vocabulariesGlobal.size() == 0) {
            weakReference.get().loadDatabaseVocabularyToDictionary();
        }

        while (vocabulariesGlobal == null || vocabulariesGlobal.size() == 0) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        weakReference.get().loadDictionaryOnTheList(vocabulariesGlobal);
        weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.GONE);
        weakReference.get().findViewById(R.id.dictionaryListView).setVisibility(View.VISIBLE);
    }
}
</code>```

And that's how I am calling it:

```<code>LoadingDictionaryAsync loadingDictionaryAsync = new LoadingDictionaryAsync((MainScreenActivity)getParent());
loadingDictionaryAsync.execute();
</code>```

EDIT:

I've tried with creating a separate file with the LoadingDictionaryAsync where static is not a problem anymore, but I still have problem with passing MainScreenActivity it, so findViewById() cannot be used.

What is the proper way of passing Activity? I want to pass it in onNavigationItemSelected() and onQueryTextChange() in SearchView?

答:
I've fixed the problem in the following way:

Moved Async classes I've created to separate files.

Switched the use of WeakReference to Context

Preceded findViewById() with ((MainScreenActivity)context).

Called the AsyncTasks with MainScreenActivity.this

So the call is:

```<code>LoadingDictionaryAsync loadingDictionaryAsync = new LoadingDictionaryAsync(MainScreenActivity.this);
loadingDictionaryAsync.execute();
</code>```

And now the AsyncTask class looks like the following:

```<code>public class LoadingDictionaryAsync extends AsyncTask<Void, Void, Void> {

private Context context;
    public LoadingDictionaryAsync(Context context) {
        this.context = context;
    }

@Override
protected void onPreExecute() {

    ((MainScreenActivity)context).findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryListView).setVisibility(View.GONE);
}

@Override
protected Void doInBackground(Void... voids) {

    if (((MainScreenActivity)context).vocabulariesGlobal == null || ((MainScreenActivity)context).vocabulariesGlobal.size() == 0) {
        ((MainScreenActivity)context).loadDatabaseVocabularyToDictionary();
    }
    while (((MainScreenActivity)context).vocabulariesGlobal == null || ((MainScreenActivity)context).vocabulariesGlobal.size() == 0) {
    }
    return null;
}

@Override
protected void onPostExecute(Void aVoid) {

    ((MainScreenActivity)context).loadDictionaryOnTheList(((MainScreenActivity)context).vocabulariesGlobal);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryLoading).setVisibility(View.GONE);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryListView).setVisibility(View.VISIBLE);
}
}
</code>```

Title: Static AsyncTask and findViewById()

Body:
I've read a lot of questions on AsyncTask problems of different kinds, but I seem not to find the problem I'm facing.

Android Studio insists on making my custom AsyncTask static with the following note:

This AsyncTask class should be static or leaks might occur

For that reason I've been trying on using WeakReference to the Activity the task runs in. Problem is that I want to use findViewById() in onPre and onPostExecute and I cannot to access the method.
I've found that:

weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);

does not produce an error in Android Studio, but it crashes the app.

How to solve the problem of not accessing findViewById() in the custom static AsyncTask?

Code generally works if I get rid of weakReference and make AsyncTask it non-static

Here's my AsyncTask: (the empty while loop is there on purpose so it waits until the global variable has some data.

public static class LoadingDictionaryAsync extends AsyncTask<Void, Void, Void> {

    private final WeakReference<MainScreenActivity> weakReference;

    private LoadingDictionaryAsync(MainScreenActivity mainScreenActivity){
        this.weakReference = new WeakReference<>(mainScreenActivity);
    }

    @Override
    protected void onPreExecute() {
        weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);
        weakReference.get().findViewById(R.id.dictionaryListView).setVisibility(View.GONE);
    }

    @Override
    protected Void doInBackground(Void... voids) {

        if (vocabulariesGlobal == null || vocabulariesGlobal.size() == 0) {
            weakReference.get().loadDatabaseVocabularyToDictionary();
        }

        while (vocabulariesGlobal == null || vocabulariesGlobal.size() == 0) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        weakReference.get().loadDictionaryOnTheList(vocabulariesGlobal);
        weakReference.get().findViewById(R.id.dictionaryLoading).setVisibility(View.GONE);
        weakReference.get().findViewById(R.id.dictionaryListView).setVisibility(View.VISIBLE);
    }
}

And that's how I am calling it:

LoadingDictionaryAsync loadingDictionaryAsync = new LoadingDictionaryAsync((MainScreenActivity)getParent());
loadingDictionaryAsync.execute();

EDIT:

I've tried with creating a separate file with the LoadingDictionaryAsync where static is not a problem anymore, but I still have problem with passing MainScreenActivity it, so findViewById() cannot be used.

What is the proper way of passing Activity? I want to pass it in onNavigationItemSelected() and onQueryTextChange() in SearchView?

Body:
I've fixed the problem in the following way:

Moved Async classes I've created to separate files.

Switched the use of WeakReference to Context

Preceded findViewById() with ((MainScreenActivity)context).

Called the AsyncTasks with MainScreenActivity.this

So the call is:

LoadingDictionaryAsync loadingDictionaryAsync = new LoadingDictionaryAsync(MainScreenActivity.this);
loadingDictionaryAsync.execute();

And now the AsyncTask class looks like the following:

public class LoadingDictionaryAsync extends AsyncTask<Void, Void, Void> {

private Context context;
    public LoadingDictionaryAsync(Context context) {
        this.context = context;
    }

@Override
protected void onPreExecute() {

    ((MainScreenActivity)context).findViewById(R.id.dictionaryLoading).setVisibility(View.VISIBLE);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryListView).setVisibility(View.GONE);
}

@Override
protected Void doInBackground(Void... voids) {

    if (((MainScreenActivity)context).vocabulariesGlobal == null || ((MainScreenActivity)context).vocabulariesGlobal.size() == 0) {
        ((MainScreenActivity)context).loadDatabaseVocabularyToDictionary();
    }
    while (((MainScreenActivity)context).vocabulariesGlobal == null || ((MainScreenActivity)context).vocabulariesGlobal.size() == 0) {
    }
    return null;
}

@Override
protected void onPostExecute(Void aVoid) {

    ((MainScreenActivity)context).loadDictionaryOnTheList(((MainScreenActivity)context).vocabulariesGlobal);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryLoading).setVisibility(View.GONE);
    ((MainScreenActivity)context).findViewById(R.id.dictionaryListView).setVisibility(View.VISIBLE);
}
}


问:
Dagger 2.11: Local Singleton when using @ContributesAndroidInjector
I have a working Dagger setup using the @ContributesAndroidInjector annotation (https://google.github.io/dagger/android.html).

```<code>        Component Application
       /                     \
Subcomponent DrawerActivity   Subcomponent SubActivity
      |
Subcomponent DrawerFragment
</code>```

In SubActivity and DrawerActivity I am using the same repository instance which is marked as @Singleton.

```<code>@Singleton
@Component(modules = {
        AndroidInjectionModule.class,
        AppModule.class,
        ActivityBuilderModule.class
})
public interface AppComponent {
    @Component.Builder
    interface Builder{
        @BindsInstance Builder application(Application application);

        AppComponent build();
    }
    void inject(App app);
}

@Module
public abstract class ActivityBuilderModule {
    @PerActivity
    @ContributesAndroidInjector(modules = {DrawerActivityModule.class,
    FragmentBuilderModule.class})
    abstract DrawerActivity bindDrawerActivity();

    @PerActivity
    @ContributesAndroidInjector(modules = {DrawerActivityModule.class})
    abstract SubActivity bindSubActivity();
}

@Module
public abstract class FragmentBuilderModule {
    @PerFragment
    @ContributesAndroidInjector(modules = DrawerFragmentModule.class)
    abstract DrawerFragment provideDrawerFragment();
}

@Singleton
public class Repository{
    private SomeClass mSomeClass;

    @Inject
    public VehicleRepositoryImpl(SomeClass someClass) {
        mSomeClass = someClass;
    }
}

public class App extends Application implements HasActivityInjector{
    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        AppComponent component = DaggerAppComponent.builder().application(this)
                .build();
        component.inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}

public class DrawerActivity extends AppCompatActivity implements HasSupportFragmentInjector{
    @Inject
    DispatchingAndroidInjector<Fragment> fragmentDispatchingAndroidInjector;

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return fragmentDispatchingAndroidInjector;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class DrawerFragment extends Fragment {
    @Inject
    ViewModelFactory mViewModelFactory; //repository gets injected into factory

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidSupportInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class SubActivity extends AppCompatActivity{
    @Inject
    Repository mRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}
</code>```

I have now the need to add a user management. This requires a LoginActivity. I don't want the repository to be avaiblable in LoginActivity. So I'd like to create a local singleton scope "UserScope" for DrawerActivity/Subactivity/DrawerFragement

```<code>              Component Application
           /                          \
   @UserScope                       @LoginScope
   Subcomponent DrawerActivity      SubComponent LoginActivity
      |                        \
Subcomponent DrawerFragment   Subcomponent SubActivity
</code>```

How can I achieve this still using the new @ContributesAndroidInjector annotation?

I want it to work like in this blogpost: http://frogermcs.github.io/building-userscope-with-dagger2/

答:
I solved my problem by doing it like in this repo:

https://github.com/ragdroid/Dahaka

Many thanks to its contributor!

Update 1: Code example added.

This graph gives a rough idea of the code example.

```<code>                 Component Application
           /                               \
   @UserScope                          @LoginScope
   Subcomponent UserComponent          SubComponent LoginActivity
      |                      \
Subcomponent DrawerActivity   Subcomponent SubActivity
      |
SubComponent DrawerFragment
</code>```

Code Example (If somethings missing please let me know in the comments):

1. Dagger Setup

AppComponent is the root of Dagger graph:

```<code>@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        AppModule.class,
        AppBindingModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
    @Component.Builder
    interface Builder{
        @BindsInstance Builder application(Application application);

        AppComponent build();
    }

    void inject(MyApp app);

    UserComponent.Builder userBuilder();

    UserManager getUserManager();
}
</code>```

Module which binds its SubComponents:

```<code>@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {

    @ContributesAndroidInjector(modules = LoginModule.class)
    @LoginScope
    abstract LoginActivity loginActivity();

}
</code>```

UserComponent holds instances of classes that are used only when user is logged in. All classes provided in UserModule.class are available as "LocalSingletons" in further subcomponents like activities and fragment components.

```<code>@UserScope
@Subcomponent(modules = {
        UserBindingModule.class,
        UserModule.class,
        AndroidSupportInjectionModule.class
})
public interface UserComponent extends AndroidInjector<DaggerApplication> {
    void inject(UserManager userManager);

    @Subcomponent.Builder
    interface Builder{
        UserComponent build();
    }
}
</code>```

UserBindingModule defines which activity-subcomponents belong to UserComponent.

```<code>@Module
public abstract class UserBindingModule {
    @ContributesAndroidInjector(modules = {DrawerBindingModule.class, AndroidSupportInjectionModule.class})
    abstract DrawerActivity bindDrawerActivity();

    @ContributesAndroidInjector
    abstract SubActivity bindSubActivity();
}
</code>```

DrawerBindingModule defines which fragment-subcomponents belong to DrawerActivityComponent.

```<code>@Module
public abstract class DrawerBindingModule {
    @DrawerFragmentScope
    @ContributesAndroidInjector(modules = DrawerFragmentModule.class)
    abstract DrawerFragment provideDrawerFragment();
}
</code>```

The UserManager handles user login/logout and all further activity injections.

```<code>@Singleton
public class UserManager implements HasActivityInjector {
    private final UserComponent.Builder userComponentBuilder;
    @Inject
    DispatchingAndroidInjector<Activity> activityInjector;

    private UserComponent userComponent;

    @Inject
    public UserManager(UserComponent.Builder builder) {
        this.userComponentBuilder = builder;
    }

    public void logIn(){
        createUserSession();
    }

    private void createUserSession() {
        userComponent = userComponentBuilder.build();
        userComponent.inject(this);
    }

    public boolean isLoggedIn() {
        return userComponent != null;
    }

    public void logOut() {
        userComponent = null;
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityInjector;
    }
}
</code>```

2. App+Activity+Fragment classes

```<code>public class MyApp extends Application implements HasActivityInjector{
    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    @Inject
    UserManager mUserManager;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        AppComponent component = DaggerAppComponent.builder().application(this)
                .build();
        component.inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return mUserManager.activityInjector();
    }
}

public class LoginActivity extends AppCompatActivity {
    Intent mOpenDrawerActivity;
    private ActivityLoginBinding binding;

    @Inject
    UserManager mUserManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        ...
    }

    void openDrawerActivity(){
        mUserManager.logIn();
        mOpenDrawerActivity = new Intent(this, DrawerActivity.class);
        startActivity(mOpenDrawerActivity);
        finish();
    }
}

public class DrawerActivity extends BaseUserActivity implements HasSupportFragmentInjector{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    private void onLogout(){
        logoutUser();
    }
}

public abstract class BaseUserActivity extends BaseActivity {
    @Inject
    UserManager userManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!userManager.isLoggedIn()) {
            finishView();
        }
    }

    @Override
    protected void androidInject() {
        AndroidInjection.inject(this);
    }

    protected void logoutUser() {
        userManager.logOut();
        finishView();
    }
}

public abstract class BaseActivity extends AppCompatActivity implements HasSupportFragmentInjector {
    @Inject
    DispatchingAndroidInjector<Fragment> injector;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        androidInject();
        super.onCreate(savedInstanceState);
    }

    protected void androidInject() {
        AndroidInjection.inject(this);
    }

    public void finishView() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return injector;
    }
}
</code>```

Body:
I have a working Dagger setup using the @ContributesAndroidInjector annotation (https://google.github.io/dagger/android.html).

        Component Application
       /                     \
Subcomponent DrawerActivity   Subcomponent SubActivity
      |
Subcomponent DrawerFragment

In SubActivity and DrawerActivity I am using the same repository instance which is marked as @Singleton.

@Singleton
@Component(modules = {
        AndroidInjectionModule.class,
        AppModule.class,
        ActivityBuilderModule.class
})
public interface AppComponent {
    @Component.Builder
    interface Builder{
        @BindsInstance Builder application(Application application);

        AppComponent build();
    }
    void inject(App app);
}

@Module
public abstract class ActivityBuilderModule {
    @PerActivity
    @ContributesAndroidInjector(modules = {DrawerActivityModule.class,
    FragmentBuilderModule.class})
    abstract DrawerActivity bindDrawerActivity();

    @PerActivity
    @ContributesAndroidInjector(modules = {DrawerActivityModule.class})
    abstract SubActivity bindSubActivity();
}

@Module
public abstract class FragmentBuilderModule {
    @PerFragment
    @ContributesAndroidInjector(modules = DrawerFragmentModule.class)
    abstract DrawerFragment provideDrawerFragment();
}

@Singleton
public class Repository{
    private SomeClass mSomeClass;

    @Inject
    public VehicleRepositoryImpl(SomeClass someClass) {
        mSomeClass = someClass;
    }
}

public class App extends Application implements HasActivityInjector{
    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        AppComponent component = DaggerAppComponent.builder().application(this)
                .build();
        component.inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}

public class DrawerActivity extends AppCompatActivity implements HasSupportFragmentInjector{
    @Inject
    DispatchingAndroidInjector<Fragment> fragmentDispatchingAndroidInjector;

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return fragmentDispatchingAndroidInjector;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class DrawerFragment extends Fragment {
    @Inject
    ViewModelFactory mViewModelFactory; //repository gets injected into factory

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidSupportInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class SubActivity extends AppCompatActivity{
    @Inject
    Repository mRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

I have now the need to add a user management. This requires a LoginActivity. I don't want the repository to be avaiblable in LoginActivity. So I'd like to create a local singleton scope "UserScope" for DrawerActivity/Subactivity/DrawerFragement

              Component Application
           /                          \
   @UserScope                       @LoginScope
   Subcomponent DrawerActivity      SubComponent LoginActivity
      |                        \
Subcomponent DrawerFragment   Subcomponent SubActivity

How can I achieve this still using the new @ContributesAndroidInjector annotation?

I want it to work like in this blogpost: http://frogermcs.github.io/building-userscope-with-dagger2/

Body:
I solved my problem by doing it like in this repo:

https://github.com/ragdroid/Dahaka

Many thanks to its contributor!

Update 1: Code example added.

This graph gives a rough idea of the code example.

                 Component Application
           /                               \
   @UserScope                          @LoginScope
   Subcomponent UserComponent          SubComponent LoginActivity
      |                      \
Subcomponent DrawerActivity   Subcomponent SubActivity
      |
SubComponent DrawerFragment

Code Example (If somethings missing please let me know in the comments):

1. Dagger Setup

AppComponent is the root of Dagger graph:

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        AppModule.class,
        AppBindingModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
    @Component.Builder
    interface Builder{
        @BindsInstance Builder application(Application application);

        AppComponent build();
    }

    void inject(MyApp app);

    UserComponent.Builder userBuilder();

    UserManager getUserManager();
}

Module which binds its SubComponents:

@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {

    @ContributesAndroidInjector(modules = LoginModule.class)
    @LoginScope
    abstract LoginActivity loginActivity();

}

UserComponent holds instances of classes that are used only when user is logged in. All classes provided in UserModule.class are available as "LocalSingletons" in further subcomponents like activities and fragment components.

@UserScope
@Subcomponent(modules = {
        UserBindingModule.class,
        UserModule.class,
        AndroidSupportInjectionModule.class
})
public interface UserComponent extends AndroidInjector<DaggerApplication> {
    void inject(UserManager userManager);

    @Subcomponent.Builder
    interface Builder{
        UserComponent build();
    }
}

UserBindingModule defines which activity-subcomponents belong to UserComponent.

@Module
public abstract class UserBindingModule {
    @ContributesAndroidInjector(modules = {DrawerBindingModule.class, AndroidSupportInjectionModule.class})
    abstract DrawerActivity bindDrawerActivity();

    @ContributesAndroidInjector
    abstract SubActivity bindSubActivity();
}

DrawerBindingModule defines which fragment-subcomponents belong to DrawerActivityComponent.

@Module
public abstract class DrawerBindingModule {
    @DrawerFragmentScope
    @ContributesAndroidInjector(modules = DrawerFragmentModule.class)
    abstract DrawerFragment provideDrawerFragment();
}

The UserManager handles user login/logout and all further activity injections.

@Singleton
public class UserManager implements HasActivityInjector {
    private final UserComponent.Builder userComponentBuilder;
    @Inject
    DispatchingAndroidInjector<Activity> activityInjector;

    private UserComponent userComponent;

    @Inject
    public UserManager(UserComponent.Builder builder) {
        this.userComponentBuilder = builder;
    }

    public void logIn(){
        createUserSession();
    }

    private void createUserSession() {
        userComponent = userComponentBuilder.build();
        userComponent.inject(this);
    }

    public boolean isLoggedIn() {
        return userComponent != null;
    }

    public void logOut() {
        userComponent = null;
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityInjector;
    }
}

2. App+Activity+Fragment classes

public class MyApp extends Application implements HasActivityInjector{
    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    @Inject
    UserManager mUserManager;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        AppComponent component = DaggerAppComponent.builder().application(this)
                .build();
        component.inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return mUserManager.activityInjector();
    }
}

public class LoginActivity extends AppCompatActivity {
    Intent mOpenDrawerActivity;
    private ActivityLoginBinding binding;

    @Inject
    UserManager mUserManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        ...
    }

    void openDrawerActivity(){
        mUserManager.logIn();
        mOpenDrawerActivity = new Intent(this, DrawerActivity.class);
        startActivity(mOpenDrawerActivity);
        finish();
    }
}

public class DrawerActivity extends BaseUserActivity implements HasSupportFragmentInjector{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    private void onLogout(){
        logoutUser();
    }
}

public abstract class BaseUserActivity extends BaseActivity {
    @Inject
    UserManager userManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!userManager.isLoggedIn()) {
            finishView();
        }
    }

    @Override
    protected void androidInject() {
        AndroidInjection.inject(this);
    }

    protected void logoutUser() {
        userManager.logOut();
        finishView();
    }
}

public abstract class BaseActivity extends AppCompatActivity implements HasSupportFragmentInjector {
    @Inject
    DispatchingAndroidInjector<Fragment> injector;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        androidInject();
        super.onCreate(savedInstanceState);
    }

    protected void androidInject() {
        AndroidInjection.inject(this);
    }

    public void finishView() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return injector;
    }
}


问:
Set default date on a textbox in aspx (not codebehind!)
I have this but it's not working:</p>

```<code><asp:TextBox runat="server" Text='<%#DateTime.Now.ToString("{0:d}")%>' ></asp:TextBox>
</code>```

答:
You have to call databind on page_load if you are going to bind data to Controls that way.</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    DataBind();
}
</code>```

Body:
I have this but it's not working:

<asp:TextBox runat="server" Text='<%#DateTime.Now.ToString("{0:d}")%>' ></asp:TextBox>

Body:
You have to call databind on page_load if you are going to bind data to Controls that way.

protected void Page_Load(object sender, EventArgs e)
{
    DataBind();
}


问:
What is the standard way of adding documentation to a JavaScript function?
I'm looking at generating API docs for a JavaScript project. Does JavaScript have anything similar to Python's docstring?</p>

```<code>function add(a, b) {
  /**
    Returns the sum of `a` and `b`.
  */
  return (a - 0) + (b - 0);
}
</code>```

答: PDoc is an in-line documentation generator for the Prototype library, written in Ruby.</p>

Body:
I'm looking at generating API docs for a JavaScript project. Does JavaScript have anything similar to Python's docstring?

function add(a, b) {
  /**
    Returns the sum of `a` and `b`.
  */
  return (a - 0) + (b - 0);
}


问:
How do I set two mutually exclusive check boxes in Jquery?
```<code>$(document).ready(function() {
            $("input:txtAge1").click(function(event) {
                if ($(txtAge1).attr("checked") == true) {
                    $(txtAge2).attr("checked", "unchecked");
                    $(txtAge2).attr("checked") == false)
                }

                if ($(txtAge2).attr("checked") == true) {
                    $(txtAge1).attr("checked", "unchecked");
                    $(txtAge1).attr("checked") == false)
                }
            });
});

<input type="checkbox" id="txtAge1" name="option1" value=""/>21<br>
<input type="checkbox" id="txtAge2" name="option2" value=""/>55<br>
</code>```

I am trying to select either one checkbox or the other. So if one box is UNchecked, it should either be not allowed or force the
other box to BE checked ...in other words, enforce either one or the other but never allow
a "undefined" condition

答:
I would use this function. Allows mutual exclusion and allows uncheking:</p>

```<code>$('#divId').find(':checkbox').click(function() {
         var state=$(this).prop("checked");
         $(':checkbox').prop("checked", false);
         $(this).prop("checked", state);
    });
</code>```

Body:
$(document).ready(function() {
            $("input:txtAge1").click(function(event) {
                if ($(txtAge1).attr("checked") == true) {
                    $(txtAge2).attr("checked", "unchecked");
                    $(txtAge2).attr("checked") == false)
                }

                if ($(txtAge2).attr("checked") == true) {
                    $(txtAge1).attr("checked", "unchecked");
                    $(txtAge1).attr("checked") == false)
                }
            });
});

<input type="checkbox" id="txtAge1" name="option1" value=""/>21

<input type="checkbox" id="txtAge2" name="option2" value=""/>55

I am trying to select either one checkbox or the other. So if one box is UNchecked, it should either be not allowed or force the
other box to BE checked ...in other words, enforce either one or the other but never allow
a "undefined" condition

Body:
I would use this function. Allows mutual exclusion and allows uncheking:

$('#divId').find(':checkbox').click(function() {
         var state=$(this).prop("checked");
         $(':checkbox').prop("checked", false);
         $(this).prop("checked", state);
    });


问:
Obtain all filenames in a directory using vim
This is the algorithm of the code:

```<code>for every *file* in a directory
  nnoremap ,*file* <C-o>:read $HOME/*file*
end
</code>```

So the problem is, I don't know how to code the "for every file in a directory".

PS: I am new to vim and I don't know if it's possible

答:
Apart from glob() (see answer from @LucHermitte), you also need :execute:

```<code>execute 'nnoremap ,' . file . ' <C-o>:read $HOME/' . file
</code>```

(or more elegantly with printf():)

```<code>execute printf('nnoremap ,%s <C-o>:read $HOME/%s', file, file)
</code>```

Description

Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:

```<code>:sleep <C-R>=timetowait<CR>m<CR>
</code>```

... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:

```<code>execute 'sleep' timetowait . 'm'
</code>```

Body:
This is the algorithm of the code:

for every *file* in a directory
  nnoremap ,*file* <C-o>:read $HOME/*file*
end

So the problem is, I don't know how to code the "for every file in a directory".

PS: I am new to vim and I don't know if it's possible

Body:
Apart from glob() (see answer from @LucHermitte), you also need :execute:

execute 'nnoremap ,' . file . ' <C-o>:read $HOME/' . file

(or more elegantly with printf():)

execute printf('nnoremap ,%s <C-o>:read $HOME/%s', file, file)

Description

Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:

:sleep <C-R>=timetowait<CR>m<CR>

... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:

execute 'sleep' timetowait . 'm'


问:
Custom navigation bar using Xamarin forms with prism broken
I'm using Prism Library for Xamarin.Forms.

And I'm going to create custom navigation bar via Control template. (Reason of creating custom navigation bar - I didn't find solution to make navigation bar transparent for display background image, also I will probably customize my navigation bar and add some controls on it).

<ControlTemplate x:Key="NavigationPageTemplate">
    <AbsoluteLayout BackgroundColor="Transparent">

        <Image AbsoluteLayout.LayoutBounds="0,0,1,1"
               AbsoluteLayout.LayoutFlags="All"
               Aspect="AspectFill"
               Source="{TemplateBinding BackgroundImageEx}" />

        <ContentView Padding="0,50,0,0"
                     AbsoluteLayout.LayoutBounds="0,0,1,1"
                     AbsoluteLayout.LayoutFlags="All">
            <ContentPresenter />
        </ContentView>

        <ContentView AbsoluteLayout.LayoutBounds="0,0,1,AutoSize"
                     AbsoluteLayout.LayoutFlags="PositionProportional, WidthProportional"
                     BackgroundColor="Transparent">
            <ContentView.Padding>
                <OnPlatform x:TypeArguments="Thickness"
                            Android="10"
                            iOS="10, 20, 10, 0" />
            </ContentView.Padding>

            <controls:ImageButton Command="{TemplateBinding GoBackCommand}"
                                  HeightRequest="30"
                                  HorizontalOptions="StartAndExpand"
                                  Source="ic_back.png"
                                  WidthRequest="30">

            </controls:ImageButton>

        </ContentView>
    </AbsoluteLayout>
</ControlTemplate>
```

<p>And my problem is to process back button press with Prism Navigation.
I've tried to process click on MyApp.xaml.cs file.</p>

<pre class="lang-xml prettyprint-override"><code>private void Button_OnClicked(object sender, EventArgs e)
{
    NavigationService.GoBackAsync();
}
</code>```

And it seems to have different navigation stack because it shows after press my first page.

I had Navigation this way:

Navigate("FirstPage"); -> Navigate(MasterDetail/NavigationPage/ViewA) -> Navigate("ViewB")
ViewB - uses Control template.

When I click custom back button on ViewB NavigationService back me to FirstPage. It is incorrect for me. I should back to ViewA!

Another question Should first page be saved when we change App.MainPage?

答:
To navigate back from ViewA to FirstPage you can intercept the back event and go back again if a variable is passed with a specific value from the ViewB page. Code Example:

Sender:

```<code>var navigationParams = new NavigationParameters();
navigationParams.Add("yourVariableName", "YourVariableValue");
_navigationService.GoBackAsync(navigationParams);
</code>```

Receiver:

```<code>public void OnNavigatedTo(NavigationParameters parameters)
        {
  string myVar = null;
            if (parameters.ContainsKey("yourVariableName"))
            {
                myVar = (string)parameters["yourVariableName"];
            }
  if(myVar=="YourVariableValue"){
     NavigationService.GoBackAsync();
  }
}
</code>```

I don't understand your second question.

Body:
I'm using Prism Library for Xamarin.Forms.

And I'm going to create custom navigation bar via Control template. (Reason of creating custom navigation bar - I didn't find solution to make navigation bar transparent for display background image, also I will probably customize my navigation bar and add some controls on it).

<ControlTemplate x:Key="NavigationPageTemplate">
    <AbsoluteLayout BackgroundColor="Transparent">

        <Image AbsoluteLayout.LayoutBounds="0,0,1,1"
               AbsoluteLayout.LayoutFlags="All"
               Aspect="AspectFill"
               Source="{TemplateBinding BackgroundImageEx}" />

        <ContentView Padding="0,50,0,0"
                     AbsoluteLayout.LayoutBounds="0,0,1,1"
                     AbsoluteLayout.LayoutFlags="All">
            <ContentPresenter />
        </ContentView>

        <ContentView AbsoluteLayout.LayoutBounds="0,0,1,AutoSize"
                     AbsoluteLayout.LayoutFlags="PositionProportional, WidthProportional"
                     BackgroundColor="Transparent">
            <ContentView.Padding>
                <OnPlatform x:TypeArguments="Thickness"
                            Android="10"
                            iOS="10, 20, 10, 0" />
            </ContentView.Padding>

            <controls:ImageButton Command="{TemplateBinding GoBackCommand}"
                                  HeightRequest="30"
                                  HorizontalOptions="StartAndExpand"
                                  Source="ic_back.png"
                                  WidthRequest="30">

            </controls:ImageButton>

        </ContentView>
    </AbsoluteLayout>
</ControlTemplate>

And my problem is to process back button press with Prism Navigation.
I've tried to process click on MyApp.xaml.cs file.

private void Button_OnClicked(object sender, EventArgs e)
{
    NavigationService.GoBackAsync();
}

And it seems to have different navigation stack because it shows after press my first page.

I had Navigation this way:

Navigate("FirstPage"); -> Navigate(MasterDetail/NavigationPage/ViewA) -> Navigate("ViewB")
ViewB - uses Control template.

When I click custom back button on ViewB NavigationService back me to FirstPage. It is incorrect for me. I should back to ViewA!

Another question Should first page be saved when we change App.MainPage?

Body:
To navigate back from ViewA to FirstPage you can intercept the back event and go back again if a variable is passed with a specific value from the ViewB page. Code Example:

Sender:

var navigationParams = new NavigationParameters();
navigationParams.Add("yourVariableName", "YourVariableValue");
_navigationService.GoBackAsync(navigationParams);

Receiver:

public void OnNavigatedTo(NavigationParameters parameters)
        {
  string myVar = null;
            if (parameters.ContainsKey("yourVariableName"))
            {
                myVar = (string)parameters["yourVariableName"];
            }
  if(myVar=="YourVariableValue"){
     NavigationService.GoBackAsync();
  }
}

I don't understand your second question.