问:
My map doesn't update after I add a new item through the putifAbsent method
My map doesnt take any new values that I add to it.
This is my Provider:

import 'package:flutter/material.dart';

import '../classes/transaction.dart';

class Transactions with ChangeNotifier {

  Map<String, Transaction> _userTransactions = {

   'ju': Transaction(amount: 45, date: DateTime.now(), title: 'socks', accountType: 'timr', notes: 'joa' , icon: Icon(Icons.today,), id: 'kololdcd', repeat: 'always')
  } ;

 Map<String, Transaction> get userTransactions {
   print (_userTransactions);
   return {..._userTransactions};

 }

   void addNewTransaction({String txTitle, double txAmount, DateTime chosenDate,
      String txAccountType, String txNotes, String txRepeat, Icon txIcon, String txId}) {

    if (txRepeat != 'Einmalig' && _userTransactions.containsKey(txId)){
    _userTransactions.update(txId, (existingItem) =>  Transaction(
      title: existingItem.title,
      amount: existingItem.amount,
      date: DateTime.now(),
      id: DateTime.now().toString(),
      accountType: existingItem.accountType,
      notes: existingItem.notes,
      repeat: existingItem.repeat,
      icon: existingItem.icon,
    ) );

    } else {
      _userTransactions.putIfAbsent(txId, ()=>  Transaction(
      title: txTitle,
      amount: txAmount,
      date: chosenDate,
      id: DateTime.now().toString(),
      accountType: txAccountType,
      notes: txNotes,
      repeat: txRepeat,
      icon: txIcon,
    ));

    }
    //final cant be changed anymore
    print (_userTransactions);
    notifyListeners();

  }

}```
</div>
</div>

This is my listener:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/transactions.dart';

import 'package:intl/intl.dart';

class TransactionList extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
   final transactionsData = Provider.of<Transactions>(context);
   final transactions = transactionsData.userTransactions;
   print (transactions);

    return transactionsData.userTransactions.isEmpty
        ? LayoutBuilder(builder: (ctx, constraints) {
            return Column(
              children: <Widget>[
                Text(
                  'Keine Transaktionen hinzugefügt. ',
                  style: Theme.of(context).textTheme.title,
                ),
                const SizedBox(height: 20),
                Container(
                  height: constraints.maxHeight * 0.6,

                ),
              ],
            );
          })
        :

                                     ListView.builder(
                 itemCount: transactions.length,
                 itemBuilder:(context, i) {
                    String key = transactions.keys.elementAt(i);
                   return Card(
      color: Colors.transparent,
      elevation: 0,
      margin: const EdgeInsets.symmetric(
        vertical: 8,
        horizontal: 5,
      ),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: Colors.transparent,
          radius: 30,
          child: Padding(
            padding: const EdgeInsets.all(6),
            child: FittedBox(
              child: Text('\$${transactions[key].amount}'),
            ),
          ),
        ),
        title: Text(
          transactions[key].title,
          style: Theme.of(context).textTheme.title,
        ),
        subtitle: Text(
           DateFormat.yMMMd().format(transactions[key].date),
        ),

      ),

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

I am calling this provider method from an other screen:

void _submitData() {

    if (_amountController.text.isEmpty) {
      return;
    }

    final enteredTitle = _titleController.text;
    final enteredAmount = double.parse(_amountController.text);
    final enteredAccount = _accountController.text;
    final enteredNotes = _notesController.text;
    final enteredRepeat = _repeatController.text;
    final enteredIcon = Icon(MyIcon.paying);
    var uuid = Uuid(options: {});

    if (enteredTitle.isEmpty ||
        enteredAmount <= 0 ||
        _selectedDate == null ||
        enteredAccount.isEmpty ||
        enteredRepeat.isEmpty) {
      return;
    } else {
      Transactions().addNewTransaction(
        txTitle: enteredTitle,
        txAmount: enteredAmount,
        chosenDate: _selectedDate,
        txAccountType: enteredAccount,
        txNotes: enteredNotes,
        txRepeat: enteredRepeat,
        txIcon: enteredIcon,
        txId: uuid.v1(options: {
          'node': [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
          'clockSeq': 0x1234,
          'mSecs': DateTime.now().millisecondsSinceEpoch,
          'nSecs': 5678
        }),
      );
    }
    Navigator.of(context).pop(context);

  }```

If I add a new pair to the map, it is shown in the addTransactionMethod (print Statement gives me the values of the new item). But as you can see in the print statement of the userTransactions my map _userTransactions doesnt take the new value, it only keeps the predifened one that I hardcoded.

This is the Debugger Konsole (the first print Statement is from the addTransaction Methode - the second one is directly from the userTransaction map:

I/flutter ( 5636): {ju: { kololdcd,socks,2020-02-14 22:33:09.616563, timr,joa,always,Icon(IconData(U+0E8DF)),45.0}, ho: { 2020-02-14 22:33:09.621559,Why not,2019-02-11 00:00:00.000, jes,cool,always,Icon(IconData(U+0E80D)),78.0}}

I/flutter ( 5636): {ju: { kololdcd,socks,2020-02-14 22:32:14.896756, timr,joa,always,Icon(IconData(U+0E8DF)),45.0}}

As you can see the Second item is missing in the second print.

As you can see in the picture the new value sin't added to the map

How can I solve the issue? I just want to add items to this _userTransactions.

Would love to hear some suggestions :)

答:
The problem is your class widget is a StatelessWidget. You can't update a StatelessWidget because being able to update it would mean it has a state that can be updated. For your approach, you will have to change your widget to being stateful:

class TransactionList extends StatefulWidget {
  TransactionList({Key key}) : super(key);

  @override
  State get createState => _TransactionListState();
}

class _TransactionListState extends State<TransactionList> {
  @override
  Widget build(BuildContext context) {
    ...
  }
}
```

<p>An alternative solution which would allow you to leave your widget as a <code>StatelessWidget</code> (which is more recommended anyway) is that instead of calling <code>Provider.of</code> directly, you use a <code>Consumer</code> to automatically pull the provider data to a builder method. The <code>Consumer</code> will also handle the rebuilding of your widget in the event that your transactions object gets updated.</p>

<pre class="lang-dart prettyprint-override"><code>class TransactionList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<Transactions>(
      builder: (context, transactionsData, _) {
        ...
      },
    );
  }
}
</code>```

Body:
My map doesnt take any new values that I add to it.
This is my Provider:

import 'package:flutter/material.dart';

import '../classes/transaction.dart';

class Transactions with ChangeNotifier {

  Map<String, Transaction> _userTransactions = {

   'ju': Transaction(amount: 45, date: DateTime.now(), title: 'socks', accountType: 'timr', notes: 'joa' , icon: Icon(Icons.today,), id: 'kololdcd', repeat: 'always')
  } ;

 Map<String, Transaction> get userTransactions {
   print (_userTransactions);
   return {..._userTransactions};

 }

   void addNewTransaction({String txTitle, double txAmount, DateTime chosenDate,
      String txAccountType, String txNotes, String txRepeat, Icon txIcon, String txId}) {

    if (txRepeat != 'Einmalig' && _userTransactions.containsKey(txId)){
    _userTransactions.update(txId, (existingItem) =>  Transaction(
      title: existingItem.title,
      amount: existingItem.amount,
      date: DateTime.now(),
      id: DateTime.now().toString(),
      accountType: existingItem.accountType,
      notes: existingItem.notes,
      repeat: existingItem.repeat,
      icon: existingItem.icon,
    ) );

    } else {
      _userTransactions.putIfAbsent(txId, ()=>  Transaction(
      title: txTitle,
      amount: txAmount,
      date: chosenDate,
      id: DateTime.now().toString(),
      accountType: txAccountType,
      notes: txNotes,
      repeat: txRepeat,
      icon: txIcon,
    ));

    }
    //final cant be changed anymore
    print (_userTransactions);
    notifyListeners();

  }

}

This is my listener:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/transactions.dart';

import 'package:intl/intl.dart';

class TransactionList extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
   final transactionsData = Provider.of<Transactions>(context);
   final transactions = transactionsData.userTransactions;
   print (transactions);

    return transactionsData.userTransactions.isEmpty
        ? LayoutBuilder(builder: (ctx, constraints) {
            return Column(
              children: <Widget>[
                Text(
                  'Keine Transaktionen hinzugefügt. ',
                  style: Theme.of(context).textTheme.title,
                ),
                const SizedBox(height: 20),
                Container(
                  height: constraints.maxHeight * 0.6,

                ),
              ],
            );
          })
        :

                                     ListView.builder(
                 itemCount: transactions.length,
                 itemBuilder:(context, i) {
                    String key = transactions.keys.elementAt(i);
                   return Card(
      color: Colors.transparent,
      elevation: 0,
      margin: const EdgeInsets.symmetric(
        vertical: 8,
        horizontal: 5,
      ),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: Colors.transparent,
          radius: 30,
          child: Padding(
            padding: const EdgeInsets.all(6),
            child: FittedBox(
              child: Text('\$${transactions[key].amount}'),
            ),
          ),
        ),
        title: Text(
          transactions[key].title,
          style: Theme.of(context).textTheme.title,
        ),
        subtitle: Text(
           DateFormat.yMMMd().format(transactions[key].date),
        ),

      ),

    );}
                  );
  }
}

I am calling this provider method from an other screen:

void _submitData() {

    if (_amountController.text.isEmpty) {
      return;
    }

    final enteredTitle = _titleController.text;
    final enteredAmount = double.parse(_amountController.text);
    final enteredAccount = _accountController.text;
    final enteredNotes = _notesController.text;
    final enteredRepeat = _repeatController.text;
    final enteredIcon = Icon(MyIcon.paying);
    var uuid = Uuid(options: {});

    if (enteredTitle.isEmpty ||
        enteredAmount <= 0 ||
        _selectedDate == null ||
        enteredAccount.isEmpty ||
        enteredRepeat.isEmpty) {
      return;
    } else {
      Transactions().addNewTransaction(
        txTitle: enteredTitle,
        txAmount: enteredAmount,
        chosenDate: _selectedDate,
        txAccountType: enteredAccount,
        txNotes: enteredNotes,
        txRepeat: enteredRepeat,
        txIcon: enteredIcon,
        txId: uuid.v1(options: {
          'node': [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
          'clockSeq': 0x1234,
          'mSecs': DateTime.now().millisecondsSinceEpoch,
          'nSecs': 5678
        }),
      );
    }
    Navigator.of(context).pop(context);

  }

If I add a new pair to the map, it is shown in the addTransactionMethod (print Statement gives me the values of the new item). But as you can see in the print statement of the userTransactions my map _userTransactions doesnt take the new value, it only keeps the predifened one that I hardcoded.

This is the Debugger Konsole (the first print Statement is from the addTransaction Methode - the second one is directly from the userTransaction map:

I/flutter ( 5636): {ju: { kololdcd,socks,2020-02-14 22:33:09.616563, timr,joa,always,Icon(IconData(U+0E8DF)),45.0}, ho: { 2020-02-14 22:33:09.621559,Why not,2019-02-11 00:00:00.000, jes,cool,always,Icon(IconData(U+0E80D)),78.0}}

I/flutter ( 5636): {ju: { kololdcd,socks,2020-02-14 22:32:14.896756, timr,joa,always,Icon(IconData(U+0E8DF)),45.0}}

As you can see the Second item is missing in the second print.

As you can see in the picture the new value sin't added to the map

How can I solve the issue? I just want to add items to this _userTransactions.

Would love to hear some suggestions :)

Body:
The problem is your class widget is a StatelessWidget. You can't update a StatelessWidget because being able to update it would mean it has a state that can be updated. For your approach, you will have to change your widget to being stateful:

class TransactionList extends StatefulWidget {
  TransactionList({Key key}) : super(key);

  @override
  State get createState => _TransactionListState();
}

class _TransactionListState extends State<TransactionList> {
  @override
  Widget build(BuildContext context) {
    ...
  }
}

An alternative solution which would allow you to leave your widget as a StatelessWidget (which is more recommended anyway) is that instead of calling Provider.of directly, you use a Consumer to automatically pull the provider data to a builder method. The Consumer will also handle the rebuilding of your widget in the event that your transactions object gets updated.

class TransactionList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<Transactions>(
      builder: (context, transactionsData, _) {
        ...
      },
    );
  }
}


来源: stackexchange

问:
html image map not working on fire fox
Hello i have a html image map however it will not work on firefox i just get the alt tag :( below is the code with all the area sections removed to keep things short.

```<code><img id="processMap" name="processMap" src="path to image" usemap="#processMap" alt=""/>
            <map id="_processMap" name="processMap">
                #all the areas
            </map>
</code>```

This works on all the other browsers i have tried (ie, chrome, safari and opera) but with firefox i just get what ever is in the alt tag :/ does anyone know whats up?

Thanks for the help!.

Updated code (still doesn't work)

```<code><img id="processMap" name="processMap" src="path to image" usemap="#processMap" alt=""/>
            <map id="processMap" name="processMap">
                #all the areas
            </map>
</code>```

答:
Id's must be specific to one element & one element only, unlike classes which can be re-used multiple times when you use htlm usemap attribute

usemap="#processMap"

the browser is using Javascript under the hood to try and find that element via the getElementById Api, or in the case of firefox it maybe using rust, but it is searching for an Id equal to the value that you specify, the same as when you use a label for an input, this is also using document.getElementById or some other Rust/C/C# variant. you've declared processMap in several different locations. Also you have not specified a type for the image such as

```<code>type="image/jpg", type="image/png", type="image/gif"..
</code>```

Plus your code does not specify a shape or the coords attributes which are necessary for the map & Area to work..
** also Image tags are self closing so you can omit the trailing / at the end.

ContentLicense: CC BY-SA 3.0

Title: html image map not working on fire fox

Body:
Hello i have a html image map however it will not work on firefox i just get the alt tag :( below is the code with all the area sections removed to keep things short.

            <map id="_processMap" name="processMap">
                #all the areas
            </map>

This works on all the other browsers i have tried (ie, chrome, safari and opera) but with firefox i just get what ever is in the alt tag :/ does anyone know whats up?

Thanks for the help!.

Updated code (still doesn't work)

            <map id="processMap" name="processMap">
                #all the areas
            </map>

Body:
Id's must be specific to one element & one element only, unlike classes which can be re-used multiple times when you use htlm usemap attribute

usemap="#processMap"

the browser is using Javascript under the hood to try and find that element via the getElementById Api, or in the case of firefox it maybe using rust, but it is searching for an Id equal to the value that you specify, the same as when you use a label for an input, this is also using document.getElementById or some other Rust/C/C# variant. you've declared processMap in several different locations. Also you have not specified a type for the image such as

type="image/jpg", type="image/png", type="image/gif"..

Plus your code does not specify a shape or the coords attributes which are necessary for the map & Area to work..
** also Image tags are self closing so you can omit the trailing / at the end.

ContentLicense: CC BY-SA 4.0


问:
Count all possible combinations no matter the column order
I have a dataset which looks like

```<code>df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2
</code>```

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

```<code>     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....
</code>```

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

答:
An option using RcppAlgos::comboGeneral to generate combinations and data.table::cube to (quoting from ?cube) Calculate aggregates at various levels of groupings producing multiple (sub-)totals.:

```<code>library(data.table)
library(RcppAlgos)

v <- unique(unlist(df[-ncol(df)]))
v <- sort(v[!is.na(v)])
nc <- length(v)

DT <- melt(setDT(df)[, rn:=.I], id.vars=c("rn", "X7"), na.rm=TRUE, variable.factor=FALSE)
combi <- DT[, as.data.table(do.call(rbind, lapply(1L:.N, function(m) {
    rcom <- comboGeneral(value, m)
    M <- matrix("", nrow=nrow(rcom), ncol=nc)

    M[cbind(rep(1L:nrow(rcom), ncol(rcom)), match(rcom, v))] <- rcom
    M
}))), .(rn, COUNT=as.integer(X7))]
ans <- cube(combi, .(COUNT=sum(COUNT)), by=paste0("V", 1:6))
setorderv(ans[complete.cases(ans)], paste0("V", 6:1))[]
</code>```

output:

```<code>    V1 V2 V3 V4 V5 V6 COUNT
 1:  A                   15
 2:     B                15
 3:  A  B                15
 4:        C              8
 5:  A     C              8
 6:     B  C              8
 7:  A  B  C              8
 8:           D          11
 9:  A        D          11
10:     B     D          11
11:  A  B     D          11
12:        C  D           8
13:  A     C  D           8
14:     B  C  D           8
15:  A  B  C  D           8
16:              E        7
17:  A           E        7
18:     B        E        7
19:  A  B        E        7
20:        C     E        7
21:  A     C     E        7
22:     B  C     E        7
23:  A  B  C     E        7
24:           D  E        7
25:  A        D  E        7
26:     B     D  E        7
27:  A  B     D  E        7
28:        C  D  E        7
29:  A     C  D  E        7
30:     B  C  D  E        7
31:  A  B  C  D  E        7
32:                 F     2
33:  A              F     2
34:     B           F     2
35:  A  B           F     2
36:        C        F     2
37:  A     C        F     2
38:     B  C        F     2
39:  A  B  C        F     2
40:           D     F     2
41:  A        D     F     2
42:     B     D     F     2
43:  A  B     D     F     2
44:        C  D     F     2
45:  A     C  D     F     2
46:     B  C  D     F     2
47:  A  B  C  D     F     2
48:              E  F     2
49:  A           E  F     2
50:     B        E  F     2
51:  A  B        E  F     2
52:        C     E  F     2
53:  A     C     E  F     2
54:     B  C     E  F     2
55:  A  B  C     E  F     2
56:           D  E  F     2
57:  A        D  E  F     2
58:     B     D  E  F     2
59:  A  B     D  E  F     2
60:        C  D  E  F     2
61:  A     C  D  E  F     2
62:     B  C  D  E  F     2
63:  A  B  C  D  E  F     2
    V1 V2 V3 V4 V5 V6 COUNT
</code>```

Body:
I have a dataset which looks like

df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

Body:
An option using RcppAlgos::comboGeneral to generate combinations and data.table::cube to (quoting from ?cube) Calculate aggregates at various levels of groupings producing multiple (sub-)totals.:

library(data.table)
library(RcppAlgos)

v <- unique(unlist(df[-ncol(df)]))
v <- sort(v[!is.na(v)])
nc <- length(v)

DT <- melt(setDT(df)[, rn:=.I], id.vars=c("rn", "X7"), na.rm=TRUE, variable.factor=FALSE)
combi <- DT[, as.data.table(do.call(rbind, lapply(1L:.N, function(m) {
    rcom <- comboGeneral(value, m)
    M <- matrix("", nrow=nrow(rcom), ncol=nc)

    M[cbind(rep(1L:nrow(rcom), ncol(rcom)), match(rcom, v))] <- rcom
    M
}))), .(rn, COUNT=as.integer(X7))]
ans <- cube(combi, .(COUNT=sum(COUNT)), by=paste0("V", 1:6))
setorderv(ans[complete.cases(ans)], paste0("V", 6:1))[]

output:

    V1 V2 V3 V4 V5 V6 COUNT
 1:  A                   15
 2:     B                15
 3:  A  B                15
 4:        C              8
 5:  A     C              8
 6:     B  C              8
 7:  A  B  C              8
 8:           D          11
 9:  A        D          11
10:     B     D          11
11:  A  B     D          11
12:        C  D           8
13:  A     C  D           8
14:     B  C  D           8
15:  A  B  C  D           8
16:              E        7
17:  A           E        7
18:     B        E        7
19:  A  B        E        7
20:        C     E        7
21:  A     C     E        7
22:     B  C     E        7
23:  A  B  C     E        7
24:           D  E        7
25:  A        D  E        7
26:     B     D  E        7
27:  A  B     D  E        7
28:        C  D  E        7
29:  A     C  D  E        7
30:     B  C  D  E        7
31:  A  B  C  D  E        7
32:                 F     2
33:  A              F     2
34:     B           F     2
35:  A  B           F     2
36:        C        F     2
37:  A     C        F     2
38:     B  C        F     2
39:  A  B  C        F     2
40:           D     F     2
41:  A        D     F     2
42:     B     D     F     2
43:  A  B     D     F     2
44:        C  D     F     2
45:  A     C  D     F     2
46:     B  C  D     F     2
47:  A  B  C  D     F     2
48:              E  F     2
49:  A           E  F     2
50:     B        E  F     2
51:  A  B        E  F     2
52:        C     E  F     2
53:  A     C     E  F     2
54:     B  C     E  F     2
55:  A  B  C     E  F     2
56:           D  E  F     2
57:  A        D  E  F     2
58:     B     D  E  F     2
59:  A  B     D  E  F     2
60:        C  D  E  F     2
61:  A     C  D  E  F     2
62:     B  C  D  E  F     2
63:  A  B  C  D  E  F     2
    V1 V2 V3 V4 V5 V6 COUNT


问:
Scala Option[(A, B)] pattern matching
I am writing a Java code generator.

I have an immutable Map that contains a mapping from java.sql.Types [Int] to a tuple of (String, String) where the first value is a Java type and the second a Java package from which to import the type if it is not imported by default (java.lang):

```<code>val SqlTypesToJavaTypeNames =
    Map(Types.BIGINT -> ("Long", None),
        Types.BINARY -> ("byte[]", None),
        Types.BIT -> ("Boolean", None),
        Types.BOOLEAN -> ("Boolean", None),
        Types.CHAR -> ("String", None),
        Types.DATE -> ("Date", Some("java.sql.Date")),
        Types.DECIMAL -> ("BigDecimal", Some("java.math.BigDecimal")),
        Types.DOUBLE -> ("Double", None),
        Types.FLOAT -> ("Float", None),
        Types.INTEGER -> ("Integer", None),
        Types.LONGNVARCHAR -> ("String", None),
        Types.LONGVARCHAR -> ("String", None),
        Types.NCHAR -> ("String", None),
        Types.NUMERIC -> ("BigDecimal", None),
        Types.NVARCHAR -> ("String", None),
        Types.REAL -> ("Float", None),
        Types.SMALLINT -> ("Short", None),
        Types.SQLXML -> ("String", None),
        Types.TIME -> ("Time", Some("java.sql.Time")),
        Types.TIMESTAMP -> ("Timestamp", Some("java.sql.Timestamp")),
        Types.TINYINT -> ("Byte", None),
        Types.VARCHAR -> ("String", None))
</code>```

I am trying to pattern match on a search of this map, where dataType is the java.sql.Types value from a database metadata:

```<code>val (javaType, importType) =
  SqlTypesToJavaTypeNames.get(dataType) match {
    case Some(jType, Some(iType)) => (jType, iType)
    case Some(jType, None) => (jType, null)
    case None => throw new IllegalStateException("Unknown translation to Java type for SQL type " + dataType)
  }
</code>```

The compiler is giving me an error on the first case (starts with case Some(jType, Some(iType))): error: wrong number of arguments for <none>: (x: (java.lang.String, Option[java.lang.String]))Some[(java.lang.String, Option[java.lang.String])]

I'm not sure what is wrong.

答:
Some doesn't extract to two values, it extracts to one.  If you want to match some pair, then you need to double-up on the parentheses:

```<code>case Some( (jType, Some(iType)) ) => (jType, iType)
</code>```

It would be nice if you could use the arrow convention as an extractor, but that sadly doesn't seem to work:

```<code>case Some(jType -> Some(iType)) => (jType, iType)
</code>```

UPDATE

Alternatively, given that you're using an Option, you could take advantage of its monadic nature and simply map over the thing:

```<code>val tpes = SqlTypesToJavaTypeNames.get(dataType)
val (javaType, importType) =
  tpes map { case (a,b) => (a, b.orNull) } getOrElse { throw ... }
</code>```

Title: Scala Option[(A, B)] pattern matching

Body:
I am writing a Java code generator.

I have an immutable Map that contains a mapping from java.sql.Types [Int] to a tuple of (String, String) where the first value is a Java type and the second a Java package from which to import the type if it is not imported by default (java.lang):

val SqlTypesToJavaTypeNames =
    Map(Types.BIGINT -> ("Long", None),
        Types.BINARY -> ("byte[]", None),
        Types.BIT -> ("Boolean", None),
        Types.BOOLEAN -> ("Boolean", None),
        Types.CHAR -> ("String", None),
        Types.DATE -> ("Date", Some("java.sql.Date")),
        Types.DECIMAL -> ("BigDecimal", Some("java.math.BigDecimal")),
        Types.DOUBLE -> ("Double", None),
        Types.FLOAT -> ("Float", None),
        Types.INTEGER -> ("Integer", None),
        Types.LONGNVARCHAR -> ("String", None),
        Types.LONGVARCHAR -> ("String", None),
        Types.NCHAR -> ("String", None),
        Types.NUMERIC -> ("BigDecimal", None),
        Types.NVARCHAR -> ("String", None),
        Types.REAL -> ("Float", None),
        Types.SMALLINT -> ("Short", None),
        Types.SQLXML -> ("String", None),
        Types.TIME -> ("Time", Some("java.sql.Time")),
        Types.TIMESTAMP -> ("Timestamp", Some("java.sql.Timestamp")),
        Types.TINYINT -> ("Byte", None),
        Types.VARCHAR -> ("String", None))

I am trying to pattern match on a search of this map, where dataType is the java.sql.Types value from a database metadata:

val (javaType, importType) =
  SqlTypesToJavaTypeNames.get(dataType) match {
    case Some(jType, Some(iType)) => (jType, iType)
    case Some(jType, None) => (jType, null)
    case None => throw new IllegalStateException("Unknown translation to Java type for SQL type " + dataType)
  }

The compiler is giving me an error on the first case (starts with case Some(jType, Some(iType))): error: wrong number of arguments for <none>: (x: (java.lang.String, Option[java.lang.String]))Some[(java.lang.String, Option[java.lang.String])]

I'm not sure what is wrong.

Body:
Some doesn't extract to two values, it extracts to one.  If you want to match some pair, then you need to double-up on the parentheses:

case Some( (jType, Some(iType)) ) => (jType, iType)

It would be nice if you could use the arrow convention as an extractor, but that sadly doesn't seem to work:

case Some(jType -> Some(iType)) => (jType, iType)

UPDATE

Alternatively, given that you're using an Option, you could take advantage of its monadic nature and simply map over the thing:

val tpes = SqlTypesToJavaTypeNames.get(dataType)
val (javaType, importType) =
  tpes map { case (a,b) => (a, b.orNull) } getOrElse { throw ... }


问:
How to create Segue which make view controller fullscreen in Xcode 11.1
When I try to create segue via storyboard it's only does open new view controller as pop out instead of fullscreen. I tried changing kind of segue from ,,Show (e.g. Push)" to others but then I get "Thread 1: signal SIGABRT"</p>

答: You need to select present modally for the segue type and then right below select the presentation style full screen:


问:
Apply a list of functions to a single matrix and retain the function names
My ultimate goal is to collect a list of summary stats for the columns of a data.frame or a matrix. For example, if I had a data.frame with three variables/columns I might want to know the mean, median and standard deviation of each column. What I would like to do is have a function that takes an arbitrary list of functions. I know something like this will do the trick

```<code>summarise = function(x, stats = list(mean, median, sd, length)){
     lapply(stats, function(stat){apply(x, 2, stat)})
}
</code>```

but how can I label the elements of the results with the name of the statistic/function applied? For example, if x is

```<code>x = matrix(1:9, nc = 3)
</code>```

then how could I write my function summarise so that I get

```<code>> summarise(x)
$mean
[1] 2 5 8

$median
[1] 2 5 8

$sd
[1] 1 1 1

$length
[1] 3 3 3
</code>```

back as the result?

答:
Simple option is to have a named output in the OP's summarise function

```<code>summarise <- function(x, stats = list(mean = mean, median = median,
       sd = sd, length = length)){
         lapply(stats, function(stat){apply(x, 2, stat)})
   }

summarise(x)
#$mean
#[1] 2 5 8

#$median
#[1] 2 5 8

#$sd
#[1] 1 1 1

#$length
#[1] 3 3 3
</code>```

Or if we use dplyr::lst or purrr::lst, it would automatically rename the list elements

```<code>summarise <- function(x, stats = dplyr::lst(mean, median,
       sd, length)){
         lapply(stats, function(stat){apply(x, 2, stat)})
   }

summarise(x)
#$mean
#[1] 2 5 8

#$median
#[1] 2 5 8

#$sd
#[1] 1 1 1

#$length
#[1] 3 3 3
</code>```

Body:
My ultimate goal is to collect a list of summary stats for the columns of a data.frame or a matrix. For example, if I had a data.frame with three variables/columns I might want to know the mean, median and standard deviation of each column. What I would like to do is have a function that takes an arbitrary list of functions. I know something like this will do the trick

summarise = function(x, stats = list(mean, median, sd, length)){
     lapply(stats, function(stat){apply(x, 2, stat)})
}

but how can I label the elements of the results with the name of the statistic/function applied? For example, if x is

x = matrix(1:9, nc = 3)

then how could I write my function summarise so that I get

> summarise(x)
$mean
[1] 2 5 8

$median
[1] 2 5 8

$sd
[1] 1 1 1

$length
[1] 3 3 3

back as the result?

Body:
Simple option is to have a named output in the OP's summarise function

summarise <- function(x, stats = list(mean = mean, median = median,
       sd = sd, length = length)){
         lapply(stats, function(stat){apply(x, 2, stat)})
   }

summarise(x)
#$mean
#[1] 2 5 8

#$median
#[1] 2 5 8

#$sd
#[1] 1 1 1

#$length
#[1] 3 3 3

Or if we use dplyr::lst or purrr::lst, it would automatically rename the list elements

summarise <- function(x, stats = dplyr::lst(mean, median,
       sd, length)){
         lapply(stats, function(stat){apply(x, 2, stat)})
   }

summarise(x)
#$mean
#[1] 2 5 8

#$median
#[1] 2 5 8

#$sd
#[1] 1 1 1

#$length
#[1] 3 3 3


问:
is it possible to integrate Google Pay in C# window form desktop application
I have Develop a Desktop Application in C# window Form. the application about reservation of Pet`s. My Manager assign me a Task to integrate google pay in This desktop application. I need to know is it possible or Not, if Yes then How ? Because in Google pay Guide it is described that this integration is for Mobile and Web.
Please Help.

Thanks

答:
Short answer is no, this isn't possible in a desktop application.

Longer answer:

The Google Pay button will generally involve launching a popup window which might not be possible to do with a webview (I haven't tried this myself)

Google Pay will only be enabled for production integration after it has been reviewed and tested by the Google Pay team and they likely won't be able to do this if it is a Windows desktop application


问:
@EnableClusterAware annotation with remote GFSH started Geode server requires HTTP configuration
We run a GFSH managed Geode cluster with several .Net clients, and now I am incorporating a new spring boot data Geode client for rSocket web endpoints with webflux. Per this question and this question I want to properly autoconfigure the SDG client application with @EnableClusterAware and @EnableClusterDefinedRegions. When I do so like this:

```<code>package app;
.. (imports) ..
@SpringBootApplication
@ComponentScan({"admin", "region", "rsocket", "webflux"}) // scans packages for @ components
@EnableLogging(logLevel="info", logFile="geode.log")
public class Web {
</code>```

and

```<code>package admin;
.. (imports) ..
@EnableClusterAware
@EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
@UseMemberName("WebServer")
public class ClientCache {
</code>```

with application.properties

```<code>spring.application.name=Web
spring.data.gemfire.pool.locators=1.2.3.4[10334]
spring.data.gemfire.pool.subscription-enabled=true
</code>```

then the client cache application starts up and it appears to get the DEFAULT pool and connect to the remote GFSH server

```<code>INFO  [main] org.apach.geode.cache.clien.inter.PoolImpl 349 start: Pool DEFAULT started with multiuser-authentication=false
INFO  [Cache Client Updater Thread  on 1.2.3.4(UAT:12900)<v1>:41001(version:UNKNOWN[ordinal=105]) port 40404] org.apach.geode.inter.cache.tier.socke.CacheClientUpdater 1581 processMessages: Cache Client Updater Thread  on 1.2.3.4(UAT:12900)<v1>:41001(version:UNKNOWN[ordinal=105]) port 40404 (1.2.3.4:40404) : ready to process messages.
</code>```

but I am not seeing the server regions being setup per @EnableClusterDefinedRegions. This means that when I navigate to http://localhost:8082/doWork the @RestController endpoint handler fails with:

```<code>Error creating bean with name 'MyRestController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.geode.cache.Region<java.lang.String, region.Object>' available: expected at least 1 bean which qualifies as autowire candidate.
</code>```

Which is because the server regions are not being initialised. If I add @EnableGemFireHttpSession then I get an error [gemfirePool] is not resolvable as a Pool in the application context and so I define my own pool like @EnableGemFireHttpSession(poolName="webPool") with an additional @Bean:

```<code>@Bean("webPool")
PoolFactoryBean sessionPool() {
    PoolFactoryBean pool = new PoolFactoryBean();
    ConnectionEndpoint ce = new ConnectionEndpoint("1.2.3.4", 10334);
    pool.setSubscriptionEnabled(true);
    pool.addLocators(ce);
    return pool;
}
</code>```

and now the @EnableClusterDefinedRegions gets to the server and instantiates all the regions I need for me. Great... but then the show fails with:

```<code>WARN  [main] org.sprin.conte.suppo.AbstractApplicationContext 558 refresh: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'gemfireClusterSchemaObjectInitializer'; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:7070/gemfire/v1/regions": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
</code>```

The only solution I can find so far is to remove @EnableClusterAware and use the annotations:

```<code>package admin;
.. (imports) ..
@EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
@UseMemberName("WebServer")
@EnableGemFireHttpSession(poolName="webPool")
public class ClientCache {
</code>```

which sets up all the regions for me, but then I am running into this issue

In build.gradle I'm using

```<code>implementation 'org.springframework.geode:spring-geode-starter:1.2.4.RELEASE'
implementation 'org.springframework.session:spring-session-data-geode:2.2.2.RELEASE'
</code>```

答:
I think there is some confusion around @EnableClusterDefinedRegions. @EnableClusterDefinedRegions uses the regions that are already declared on your server to configure your client regions, not the other way around. What it sounds like you want is @EnableClusterConfiguration, which will push regions defined by your client to the server. However, you don't need to declare @EnableClusterConfiguration explicitly, because @ClusterAware is meta-annotated with @EnableClusterConfiguration.

As for why your regions are not being created, I'm guessing that your region definitions are not being found. I notice your ClientCache class is not annotated with @Component even though you are component scanning its package; is the class in which you defined your region annotate with @Component? If not, try adding it.

Body:
We run a GFSH managed Geode cluster with several .Net clients, and now I am incorporating a new spring boot data Geode client for rSocket web endpoints with webflux. Per this question and this question I want to properly autoconfigure the SDG client application with @EnableClusterAware and @EnableClusterDefinedRegions. When I do so like this:

package app;
.. (imports) ..
@SpringBootApplication
@ComponentScan({"admin", "region", "rsocket", "webflux"}) // scans packages for @ components
@EnableLogging(logLevel="info", logFile="geode.log")
public class Web {

and

package admin;
.. (imports) ..
@EnableClusterAware
@EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
@UseMemberName("WebServer")
public class ClientCache {

with application.properties

spring.application.name=Web
spring.data.gemfire.pool.locators=1.2.3.4[10334]
spring.data.gemfire.pool.subscription-enabled=true

then the client cache application starts up and it appears to get the DEFAULT pool and connect to the remote GFSH server

INFO  [main] org.apach.geode.cache.clien.inter.PoolImpl 349 start: Pool DEFAULT started with multiuser-authentication=false
INFO  [Cache Client Updater Thread  on 1.2.3.4(UAT:12900)<v1>:41001(version:UNKNOWN[ordinal=105]) port 40404] org.apach.geode.inter.cache.tier.socke.CacheClientUpdater 1581 processMessages: Cache Client Updater Thread  on 1.2.3.4(UAT:12900)<v1>:41001(version:UNKNOWN[ordinal=105]) port 40404 (1.2.3.4:40404) : ready to process messages.

but I am not seeing the server regions being setup per @EnableClusterDefinedRegions. This means that when I navigate to http://localhost:8082/doWork the @RestController endpoint handler fails with:

Error creating bean with name 'MyRestController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.geode.cache.Region<java.lang.String, region.Object>' available: expected at least 1 bean which qualifies as autowire candidate.

Which is because the server regions are not being initialised. If I add @EnableGemFireHttpSession then I get an error [gemfirePool] is not resolvable as a Pool in the application context and so I define my own pool like @EnableGemFireHttpSession(poolName="webPool") with an additional @Bean:

@Bean("webPool")
PoolFactoryBean sessionPool() {
    PoolFactoryBean pool = new PoolFactoryBean();
    ConnectionEndpoint ce = new ConnectionEndpoint("1.2.3.4", 10334);
    pool.setSubscriptionEnabled(true);
    pool.addLocators(ce);
    return pool;
}

and now the @EnableClusterDefinedRegions gets to the server and instantiates all the regions I need for me. Great... but then the show fails with:

WARN  [main] org.sprin.conte.suppo.AbstractApplicationContext 558 refresh: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'gemfireClusterSchemaObjectInitializer'; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:7070/gemfire/v1/regions": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect

The only solution I can find so far is to remove @EnableClusterAware and use the annotations:

package admin;
.. (imports) ..
@EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
@UseMemberName("WebServer")
@EnableGemFireHttpSession(poolName="webPool")
public class ClientCache {

which sets up all the regions for me, but then I am running into this issue

In build.gradle I'm using

implementation 'org.springframework.geode:spring-geode-starter:1.2.4.RELEASE'
implementation 'org.springframework.session:spring-session-data-geode:2.2.2.RELEASE'


问:
Getting back to a CSS position sticky element with JavaScript?
I have a page where all sections fill the entire screen and are positioned with CSS position: sticky; in order to achieve a layered effect. See here:

https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark

This all works great and as expected.

The problem comes however from navigating between these areas with JavaScript. If you try using the menu, you can see that the links will work on sections that we haven't fully gotten to yet (and therefore not "sticky") but does not allow you to "go back up" the page.

I believe this is an issue with el.getBoundingClientRect() once an element has become "sticky", its top value becomes essentially always zero.

Here I am using a small library called Jump.js to jump around but even in vanilla JS this issue would still be the same, as the problem is a result of the calculation from when the element becomes sticky.

Is there any way to find the original position for each section before it was sticky? At least that way I could navigate the user by setting the scroll position manually.

I am using Vue.js but that does not affect the issue at hand which is CSS and JS related.

App.vue

```<code><template>
  <main id="app">
    <ul class="menu">
      <li @click="goTo('A')">Section A</li>
      <li @click="goTo('B')">Section B</li>
      <li @click="goTo('C')">Section C</li>
      <li @click="goTo('D')">Section D</li>
      <li @click="goTo('E')">Section E</li>
    </ul>
    <SectionItem id="A" color="red"/>
    <SectionItem id="B" color="green"/>
    <SectionItem id="C" color="blue"/>
    <SectionItem id="D" color="orange"/>
    <SectionItem id="E" color="purple"/>
  </main>
</template>

<script>
import jump from "jump.js";
import SectionItem from "./components/SectionItem.vue";

export default {
  name: "App",
  components: {
    SectionItem
  },
  methods: {
    goTo(id) {
      jump(`#${id}`, {
        duration: 300
      });
    }
  }
};
</script>
</code>```

SectionItem.vue

```<code><template>
  <div :id="id" class="SectionItem" :style="styles">
    <p>I am section item: {{ id }}</p>
  </div>
</template>

<script>
export default {
  name: "SectionItem",
  props: {
    id: {
      type: String,
      required: true
    },
    color: {
      type: String,
      required: true
    }
  },
  computed: {
    styles() {
      return {
        backgroundColor: this.color
      };
    }
  }
};
</script>

<style>
.SectionItem {
  position: sticky;
  top: 0;
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  color: white;
  border: 10px solid white;
}
</style>
</code>```

I'm looking for any reasonable solutions that get get the auto-scrolling to work in both directions. Many thanks for your time.

答:
JumpJS has an option to pass in a number instead of a selector, so one way is to grab the initial section tops in mounted() and use them in gotoId().

The jump(number) call expects a number relative to location(), which is window.scrollY || window.pageYOffset, so we have to change it to an absolute by passing the negative to the offset option.

export default {
  name: "App",
  components: {
    SectionItem
  },
  data() {
    return {
      tops: {}
    }
  },
  mounted() {
    this.tops = this.$children.reduce((acc, child) => {
      acc[child.id] = child.$el.getBoundingClientRect().top;
      return acc;
    }, {})
  },
  methods: {
    goTo(id) {
      const offset = -(window.scrollY || window.pageYOffset); // make jump absolute
      jump(this.tops[id], { duration: 300, offset });
    }
  }
};
```

Body:
I have a page where all sections fill the entire screen and are positioned with CSS position: sticky; in order to achieve a layered effect. See here:

https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark

This all works great and as expected.

The problem comes however from navigating between these areas with JavaScript. If you try using the menu, you can see that the links will work on sections that we haven't fully gotten to yet (and therefore not "sticky") but does not allow you to "go back up" the page.

I believe this is an issue with el.getBoundingClientRect() once an element has become "sticky", its top value becomes essentially always zero.

Here I am using a small library called Jump.js to jump around but even in vanilla JS this issue would still be the same, as the problem is a result of the calculation from when the element becomes sticky.

Is there any way to find the original position for each section before it was sticky? At least that way I could navigate the user by setting the scroll position manually.

I am using Vue.js but that does not affect the issue at hand which is CSS and JS related.

App.vue

<template>

Section A

Section B

Section C

Section D

Section E

    <SectionItem id="A" color="red"/>
    <SectionItem id="B" color="green"/>
    <SectionItem id="C" color="blue"/>
    <SectionItem id="D" color="orange"/>
    <SectionItem id="E" color="purple"/>

</template>

SectionItem.vue

<template>

I am section item: {{ id }}

</template>

I'm looking for any reasonable solutions that get get the auto-scrolling to work in both directions. Many thanks for your time.


问:
What is wrong with my semi-advanced PostgreSQL query? (Related to calculating with times and time intervals.)
Goal:

Have a column (which doesn't exist in the table) representing the number of seconds left until the next time a recurring event is to take place, which is determined by "last done" (timestamptz) combined with the "time span string" column, which is a string such as "7 days" or "25 minutes" or "2 weeks" (standard PG compatible interval strings).

The query:

```<code>SELECT
    *,
    now() - "last done" - "time span string"::interval AS "seconds left until next"
FROM "recurring events"
ORDER BY "seconds left until next" DESC NULLS LAST;
</code>```

The "seconds left until next" column bizarrely gets values such as:

```<code>-1 days +00:32:04.389802
</code>```

Expected value example:

```<code>123456
</code>```

I don't understand why it's not calculating with the columns. It seems to be constructing a string of their values in an interpreted manner or something. I don't know how to describe it.

I've tried to ::integer the AS expression, but that just gives me the error:

```<code>ERROR: cannot cast type interval to integer
</code>```

The question isn't so much about the correct "formula"/order of the actual expression as the fact that it doesn't turn the column (or cell, rather) into an integer (representing the number of seconds left for that event until the next time).

答:
The value that you are subtracting already looks like a number of seconds.  So, just subtract the two date/times and then convert to seconds and subtract the time span:</p>

```<code>extract(epoch from (now() - "last done")) - "time span string"
</code>```

Body:
Goal:

Have a column (which doesn't exist in the table) representing the number of seconds left until the next time a recurring event is to take place, which is determined by "last done" (timestamptz) combined with the "time span string" column, which is a string such as "7 days" or "25 minutes" or "2 weeks" (standard PG compatible interval strings).

The query:

SELECT
    *,
    now() - "last done" - "time span string"::interval AS "seconds left until next"
FROM "recurring events"
ORDER BY "seconds left until next" DESC NULLS LAST;

The "seconds left until next" column bizarrely gets values such as:

-1 days +00:32:04.389802

Expected value example:

123456

I don't understand why it's not calculating with the columns. It seems to be constructing a string of their values in an interpreted manner or something. I don't know how to describe it.

I've tried to ::integer the AS expression, but that just gives me the error:

ERROR: cannot cast type interval to integer

The question isn't so much about the correct "formula"/order of the actual expression as the fact that it doesn't turn the column (or cell, rather) into an integer (representing the number of seconds left for that event until the next time).

Body:
The value that you are subtracting already looks like a number of seconds.  So, just subtract the two date/times and then convert to seconds and subtract the time span:

extract(epoch from (now() - "last done")) - "time span string"


问:
How to restrict only a subset of WebApi authorize routes?
We have an application which requires some users to be unable to access the majority of available routes, and only able to access a few. We are using standard .net [anonymous] annotations for the public calls, but need to add some additional layer in between allowing some calls and not allowing others.

Is there a way to add custom logic to the authorization function based on some annotation?

答:
Yes, You are in need of policy based authorisation.

At the glance You need to:

Add policy configuration (name and set of rules that have to be satisfy to concider a user as a member of that group defined by the policy) as a part of ConfigureServices(IServiceCollection) configuration,

Define IAuthorizationRequirement for the policy. Those must be satisfied in order to clasify user as a part of the policy. Those requirements are going to be validated by IAuthorizationHandler<T> that must be regisered as a normal service. Actually this is the guy which decide if the rule is ok against a user or not, by calling either Success or Fail on the context given. We are not returning true or false here, just calling one of thise two methods to make a decision.

Add proper attributes to Your either controllers and/or actions.

Using policy is a more generic approach
than roles but You can also use them if You already have them defined. Policies are more like what You must have to pass" while role based autorisation in more like "who You are".


问:
Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?
I read a csv file into a pandas dataframe, and would like to convert the columns with binary answers from strings of yes/no to integers of 1/0. Below, I show one of such columns ("sampleDF" is the pandas dataframe).

```<code>In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object
</code>```

Help is much appreciated!

答:
I used the preprocesssing function from sklearn. First you create an encoder.

```<code>e = preprocessing.LabelEncoder()
</code>```

Then for each attribute or characteristic in the data use the label encoder to transform it into an integer value

```<code>size = le.fit_transform(list(data["size"]))
color = le.fit_transform(list(data["color"]))
</code>```

It's converting a list of all the "size" or "color" attributes, and converting that into a list of their corresponding integer values. To put all of this into one list, use the zip function.

It is not going to be in the same format as the csv file; it will be a giant list of everything.

```<code>data = list(zip(buying, size))
</code>```

Hopefully I explained that somewhat clearly.

Body:
I read a csv file into a pandas dataframe, and would like to convert the columns with binary answers from strings of yes/no to integers of 1/0. Below, I show one of such columns ("sampleDF" is the pandas dataframe).

In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object

Help is much appreciated!

Body:
I used the preprocesssing function from sklearn. First you create an encoder.

e = preprocessing.LabelEncoder()

Then for each attribute or characteristic in the data use the label encoder to transform it into an integer value

size = le.fit_transform(list(data["size"]))
color = le.fit_transform(list(data["color"]))

It's converting a list of all the "size" or "color" attributes, and converting that into a list of their corresponding integer values. To put all of this into one list, use the zip function.

It is not going to be in the same format as the csv file; it will be a giant list of everything.

data = list(zip(buying, size))

Hopefully I explained that somewhat clearly.


问:
ReactDOM.findDOMNode() using React.Children child
I'm trying to access a component's specific child DOM node like this:

```<code>let targetChild = null;
React.Children.forEach(children, child => {
    if (child.type.displayName === 'TargetElement') {
        targetChild = child;
    }
});

const targetEl = ReactDOM.findDOMNode(targetChild);
</code>```

However, I keep getting the error:

Uncaught Error: Argument appears to not be a ReactComponent.

When I log out the typeof targetChild I get object. Does anyone know how to fix this? Thanks!

答:
In order to get the DOM element of a particular React component instance, you need to use the Callback Refs.

Here's a demo for you:

const children = ['Bob', 'Jeff', 'Kate'];
const TARGET_NODE = 'Jeff';
let jeffRef;

const setRef = (el, label) => {
 if(label === TARGET_NODE) {
  jeffRef = el;
 }
}

const SampleApp = ({children}) => (

   {children.map((child, index) => (

 setRef(el, child)}>{child}

 ))}

)

ReactDOM.render(<SampleApp children={children}/>, document.querySelector("#app"))

console.log(jeffRef) // Should output:
Jeff
```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

PS: In my opinion, accessing DOM elements can be avoided in most cases. You might want to reconsider doing that. You can control/update the element using component state instead.

Body:
I'm trying to access a component's specific child DOM node like this:

let targetChild = null;
React.Children.forEach(children, child => {
    if (child.type.displayName === 'TargetElement') {
        targetChild = child;
    }
});

const targetEl = ReactDOM.findDOMNode(targetChild);

However, I keep getting the error:

Uncaught Error: Argument appears to not be a ReactComponent.

When I log out the typeof targetChild I get object. Does anyone know how to fix this? Thanks!

Body:
In order to get the DOM element of a particular React component instance, you need to use the Callback Refs.

Here's a demo for you:

const children = ['Bob', 'Jeff', 'Kate'];
const TARGET_NODE = 'Jeff';
let jeffRef;

const setRef = (el, label) => {
 if(label === TARGET_NODE) {
  jeffRef = el;
 }
}

const SampleApp = ({children}) => (
 <ul>
   {children.map((child, index) => (
      <li key={index} ref={el => setRef(el, child)}>{child}</li>
 ))}
 </ul>
)

ReactDOM.render(<SampleApp children={children}/>, document.querySelector("#app"))

console.log(jeffRef) // Should output: <li>Jeff</li>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

PS: In my opinion, accessing DOM elements can be avoided in most cases. You might want to reconsider doing that. You can control/update the element using component state instead.


问:
SpringBoot: Imp SpringSecurity : while login with user/pass getting Screen error msg "User is disabled"
I just start implementing SpringSecurity but post login getting Error Message on Screen "User is disabled"

IT'S WORKING VERY WELL FOR DEFAULT .
WHILE HITTING WITH /user or /admin and trying to login it's showing "User is disable"

I am following below step:

First created schema.sql (under resource folder)

CREATE TABLE USERS (
    USERNAME VARCHAR(128) PRIMARY KEY,
    PASSWORD VARCHAR(128) NOT NULL,
    ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL
);

CREATE TABLE AUTHORITIES (
    USERNAME VARCHAR(128) NOT NULL,
    AUTHORITY VARCHAR(128) NOT NULL
);

ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY);
ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME);
```</li>
<li><p>Created "data.sql" under resource folder</p>

<pre class="lang-sql prettyprint-override"><code>insert into USERS(USERNAME,PASSWORD,ENABLED) VALUES ('user','pass','Y');
insert into USERS(USERNAME,PASSWORD,ENABLED) VALUES ('admin','pass','Y');
insert into AUTHORITIES (USERNAME,AUTHORITY) values ('user','ROLE_USER');
insert into AUTHORITIES (USERNAME,AUTHORITY) values ('admin','ROLE_ADMIN');
</code>```

HomeResource.JAVA ( This is a controller class API)

package com.example.callCenter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeResource{

    @GetMapping("/")
    public String home(){
        return("
Welcome home page..
");
    }

    @GetMapping("/user")
    public String user()
    {
        return ("
Welcome User page
");
    }

    @GetMapping("/admin")
    public String admin()
    {
        return("
Welcome Admin page
");
    }
}
```</li>
<li><p>SecurityConfiguration.java ( This is enable the Spring Form PAGE)</p>

<pre class="lang-java prettyprint-override"><code>package com.example.callCenter;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select username,password,enabled "
                        + "from users "
                        + "where username = ?")
            .authoritiesByUsernameQuery("select username,AUTHORITY  "
                        + "from AUTHORITIES "
                        + "where username = ?");

        // This beloe code is default implementation with MySQL database
        // auth.jdbcAuthentication()
        //         .dataSource(dataSource)
        //         .withDefaultSchema()
        //         .withUser(
        //                     User.withUsername("user")
        //                     .password("pass")
        //                     .roles("USER")

        //         )
        //         .withUser(
        //                     User.withUsername("admin")
        //                     .password("pass")
        //                     .roles("ADMIN")
        //         );

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("ADMIN","USER")
                .antMatchers("/").permitAll()
                .and().formLogin();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder()
    {
        return NoOpPasswordEncoder.getInstance();
    }

}
</code>```

CallApplication.java

package com.example.callCenter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CallApplication {

    public static void main(String[] args) {
        SpringApplication.run(CallCenterApplication.class, args);
    }

}
```

<p><strong>pom.xml :</strong> given all the dependency that is not a issue because form is opening</p>

<p><strong>application.properties :</strong></p>

```spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=

spring.jpa.show_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.format_sql=true
```

I added almost all the details there are nothing pending from my side but now I want some one assistance why it's not allow me to call the user and allow me to login.

答:
The issue here is with the value stored in column

ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL

JdbcUserDetailsManager.loadUsersByUsername(String username) has the following code logic to populate its properties when creating User object.

```<code>                String userName = rs.getString(1);
                String password = rs.getString(2);
                boolean enabled = rs.getBoolean(3);
</code>```

To get the enabled status ,  ResultSet.getBoolean() is used and the java docs for the same mentions the following

Retrieves the value of the designated column in the current row of
  this ResultSet object as a boolean in the Java programming language.

If the designated column has a datatype of CHAR or VARCHAR and
  contains a "0" or has a datatype of BIT, TINYINT, SMALLINT, INTEGER or
  BIGINT and contains a 0, a value of false is returned. If the
  designated column has a datatype of CHAR or VARCHAR and contains a "1"
  or has a datatype of BIT, TINYINT, SMALLINT, INTEGER or BIGINT and
  contains a 1, a value of true is returned.

In the above code , the correct values for enabled/disabled are '1' and '0' respectively.

Body:
I just start implementing SpringSecurity but post login getting Error Message on Screen "User is disabled"

IT'S WORKING VERY WELL FOR DEFAULT .
WHILE HITTING WITH /user or /admin and trying to login it's showing "User is disable"

I am following below step:

First created schema.sql (under resource folder)

CREATE TABLE USERS (
    USERNAME VARCHAR(128) PRIMARY KEY,
    PASSWORD VARCHAR(128) NOT NULL,
    ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL
);

CREATE TABLE AUTHORITIES (
    USERNAME VARCHAR(128) NOT NULL,
    AUTHORITY VARCHAR(128) NOT NULL
);

ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY);
ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME);

Created "data.sql" under resource folder

insert into USERS(USERNAME,PASSWORD,ENABLED) VALUES ('user','pass','Y');
insert into USERS(USERNAME,PASSWORD,ENABLED) VALUES ('admin','pass','Y');
insert into AUTHORITIES (USERNAME,AUTHORITY) values ('user','ROLE_USER');
insert into AUTHORITIES (USERNAME,AUTHORITY) values ('admin','ROLE_ADMIN');

HomeResource.JAVA ( This is a controller class API)

package com.example.callCenter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeResource{

    @GetMapping("/")
    public String home(){
        return("
Welcome home page..
");
    }

    @GetMapping("/user")
    public String user()
    {
        return ("
Welcome User page
");
    }

    @GetMapping("/admin")
    public String admin()
    {
        return("
Welcome Admin page
");
    }
}

SecurityConfiguration.java ( This is enable the Spring Form PAGE)

package com.example.callCenter;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select username,password,enabled "
                        + "from users "
                        + "where username = ?")
            .authoritiesByUsernameQuery("select username,AUTHORITY  "
                        + "from AUTHORITIES "
                        + "where username = ?");

        // This beloe code is default implementation with MySQL database
        // auth.jdbcAuthentication()
        //         .dataSource(dataSource)
        //         .withDefaultSchema()
        //         .withUser(
        //                     User.withUsername("user")
        //                     .password("pass")
        //                     .roles("USER")

        //         )
        //         .withUser(
        //                     User.withUsername("admin")
        //                     .password("pass")
        //                     .roles("ADMIN")
        //         );

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("ADMIN","USER")
                .antMatchers("/").permitAll()
                .and().formLogin();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder()
    {
        return NoOpPasswordEncoder.getInstance();
    }

}

CallApplication.java

package com.example.callCenter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CallApplication {

    public static void main(String[] args) {
        SpringApplication.run(CallCenterApplication.class, args);
    }

}

pom.xml : given all the dependency that is not a issue because form is opening

application.properties :

spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=

spring.jpa.show_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.format_sql=true

I added almost all the details there are nothing pending from my side but now I want some one assistance why it's not allow me to call the user and allow me to login.

Body:
The issue here is with the value stored in column

ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL

JdbcUserDetailsManager.loadUsersByUsername(String username) has the following code logic to populate its properties when creating User object.

                String userName = rs.getString(1);
                String password = rs.getString(2);
                boolean enabled = rs.getBoolean(3);

To get the enabled status ,  ResultSet.getBoolean() is used and the java docs for the same mentions the following

Retrieves the value of the designated column in the current row of
  this ResultSet object as a boolean in the Java programming language.

If the designated column has a datatype of CHAR or VARCHAR and
  contains a "0" or has a datatype of BIT, TINYINT, SMALLINT, INTEGER or
  BIGINT and contains a 0, a value of false is returned. If the
  designated column has a datatype of CHAR or VARCHAR and contains a "1"
  or has a datatype of BIT, TINYINT, SMALLINT, INTEGER or BIGINT and
  contains a 1, a value of true is returned.

In the above code , the correct values for enabled/disabled are '1' and '0' respectively.


问:
POST request not working with JSON on POSTMAN
so I just began to learn some back end work, and I learned POSTMAN is a great tool for testing HTTP request methods. I have POSTMAN installed on my windows PC. I am running into a problem, in which whenever I want to test out POST method for creating an item, I just see "sending request" on POSTMAN without having a result.

My codes are the following,

```<code>const express = require('express');
const app = express();
const contacts = [{id:4}];
const contact_id = 1

const PORT = 3000;

app.get('/',(req,res)=>{
    res.send(`welcome to ${contacts}`)
})

app.post('/hello',(req,res)=>{
    const contact = {
        id:contact_id+1
    }
    contacts.push(contact);
})

app.listen(3000,()=>{
    console.log(`Server started on ${PORT}`)
})
</code>```

What could be the problem?

答:
As pzaenger correctly pointed out, you are never closing the connection on the server end with a res.end(), res.send() or res.json().

You need to close the connection with one of these methods, so that POSTMAN will receive your server's data (result):

app.post('/hello',(req,res)=>{
    const contact = {
        id: contact_id+1
    }
    contacts.push( contact );
    res.json( contacts );
});
```

Body:
so I just began to learn some back end work, and I learned POSTMAN is a great tool for testing HTTP request methods. I have POSTMAN installed on my windows PC. I am running into a problem, in which whenever I want to test out POST method for creating an item, I just see "sending request" on POSTMAN without having a result.

My codes are the following,

const express = require('express');
const app = express();
const contacts = [{id:4}];
const contact_id = 1

const PORT = 3000;

app.get('/',(req,res)=>{
    res.send(`welcome to ${contacts}`)
})

app.post('/hello',(req,res)=>{
    const contact = {
        id:contact_id+1
    }
    contacts.push(contact);
})

app.listen(3000,()=>{
    console.log(`Server started on ${PORT}`)
})

What could be the problem?


问:
How to combine two scopes with OR
I have a tag feed and a friend feed.
I want to combine these two and build the ultimate "all" feed.

For friend feed:

```<code>class Post < ActiveRecord::Base
  scope :friendfeed, lambda{|x| followed_by}

  def self.followed_by(user)
    where("user_id IN (?) OR user_id = ?", user.watched_ids, user.id)
  end
end
</code>```

For tag feed:

```<code>class Post < ActiveRecord::Base
  scope :tagfeed, lambda{|x| infatuated_with}

  def self.infatuated_with(user)
    joins(:attachments).where("attachments.tag_id IN (?)", user.tags).select("DISTINCT pages.*")
  end
end
</code>```

And I would call something like this from the controller (I'm using Kaminari gem for pagination):

```<code>@tag_feed = Post.tagfeed(current_user).page(params[:page]).per(21)
@friend_feed = Post.friendfeed(current_user).page(params[:page]).per(21)
</code>```

Now I want to have a universal feed, but I'm lost. Scopes are meant for narrowing down, but in this case I'm trying to do an OR operation. Doing stuff like

```<code>@mother_of_all_feed = @tag_feed + @friend_feed
</code>```

would be redundant, and I wouldn't be able to control the number of posts appearing on a single page. How can I go about doing this? Thanks!

By the way, for tags I have association set up like this:

```<code>class Post < ActiveRecord::Base
  has_many :attachments
  has_many :tags, :through => :attachments
end

class Tag < ActiveRecord::Base
  has_many :attachments
  has_many :posts, :through => :attachments
end

class Attachment < ActiveRecord::Base
  belongs_to :tag
  belongs_to :post
end
</code>```

答:
Here's an example of how I combined two scopes.</p>

```<code>scope :reconcilable, -> do
  scopes = [
    with_matching_insurance_payment_total,
    with_zero_insurance_payments_and_zero_amount
  ]

  where('id in (?)', scopes.flatten.map(&:id))
end
</code>```

Title: How to combine two scopes with OR

Body:
I have a tag feed and a friend feed.
I want to combine these two and build the ultimate "all" feed.

For friend feed:

class Post < ActiveRecord::Base
  scope :friendfeed, lambda{|x| followed_by}

  def self.followed_by(user)
    where("user_id IN (?) OR user_id = ?", user.watched_ids, user.id)
  end
end

For tag feed:

class Post < ActiveRecord::Base
  scope :tagfeed, lambda{|x| infatuated_with}

  def self.infatuated_with(user)
    joins(:attachments).where("attachments.tag_id IN (?)", user.tags).select("DISTINCT pages.*")
  end
end

And I would call something like this from the controller (I'm using Kaminari gem for pagination):

@tag_feed = Post.tagfeed(current_user).page(params[:page]).per(21)
@friend_feed = Post.friendfeed(current_user).page(params[:page]).per(21)

Now I want to have a universal feed, but I'm lost. Scopes are meant for narrowing down, but in this case I'm trying to do an OR operation. Doing stuff like

@mother_of_all_feed = @tag_feed + @friend_feed

would be redundant, and I wouldn't be able to control the number of posts appearing on a single page. How can I go about doing this? Thanks!

By the way, for tags I have association set up like this:

class Post < ActiveRecord::Base
  has_many :attachments
  has_many :tags, :through => :attachments
end

class Tag < ActiveRecord::Base
  has_many :attachments
  has_many :posts, :through => :attachments
end

class Attachment < ActiveRecord::Base
  belongs_to :tag
  belongs_to :post
end

Body:
Here's an example of how I combined two scopes.

scope :reconcilable, -> do
  scopes = [
    with_matching_insurance_payment_total,
    with_zero_insurance_payments_and_zero_amount
  ]

  where('id in (?)', scopes.flatten.map(&:id))
end


问:
What does this traceback error mean when running this python script in Anaconda?
New to programming. Installed Anaconda on a Windows 10 machine. Had some issues running updates.

While in Base environment, I installed my first Git repo successfully:

```<code>(base) C:\Users\samsung\Anaconda3\pkgs>pip install git+git://github.com/json-transformations/jsonflatten.git
Collecting git+git://github.com/json-transformations/jsonflatten.git
  Cloning git://github.com/json-transformations/jsonflatten.git to c:\users\samsung\appdata\local\temp\pip-req-build-zeiezw
  Running command git clone -q git://github.com/json-transformations/jsonflatten.git 'C:\Users\samsung\AppData\Local\Temp\p
Collecting jsoncut
  Downloading jsoncut-0.6-py2.py3-none-any.whl (17 kB)
Requirement already satisfied: click>=6.0 in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten==0.2) (7.0)
Requirement already satisfied: colorama in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten==0.2) (0
Requirement already satisfied: pygments in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten==0.2) (2
Building wheels for collected packages: jsonflatten
  Building wheel for jsonflatten (setup.py) ... done
  Created wheel for jsonflatten: filename=jsonflatten-0.2-py2.py3-none-any.whl size=8116 sha256=029aafde944303cbfe872e86a13
  Stored in directory: C:\Users\samsung\AppData\Local\Temp\pip-ephem-wheel-cache-so8173tt\wheels\8f\02\52\37295acfd1368a3d2
Successfully built jsonflatten
Installing collected packages: jsoncut, jsonflatten
Successfully installed jsoncut-0.6 jsonflatten-0.2

(base) C:\Users\samsung\Anaconda3\pkgs>pip install jsonflatten
Requirement already satisfied: jsonflatten in c:\users\samsung\anaconda3\lib\site-packages (0.2)
Requirement already satisfied: click>=6.0 in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten) (7.0)
Requirement already satisfied: jsoncut in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten) (0.6)
Requirement already satisfied: pygments in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten) (2.5.2)
Requirement already satisfied: colorama in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten) (0.4.3)
</code>```

I then ran jsonflatten forecast.json as a test (as well as jsonflatten C:\Users\samsung.spyder-py3\forecast.json) as the readme suggests and got the output below. I ran from base as myenv (Python) spit out a message saying jsonflatten is not recognized as a command.

```<code>(base) C:\Users\samsung\.spyder-py3>jsonflatten C:\Users\samsung\.spyder-py3\forecast.json
Traceback (most recent call last):
  File "c:\users\samsung\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\samsung\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\samsung\Anaconda3\Scripts\jsonflatten.exe\__main__.py", line 7, in <module>
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 717, in main
    rv = self.invoke(ctx)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsonflatten\cli.py", line 63, in main
    output(ctx, results, indent=4, is_json=True)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsoncut\cli.py", line 59, in output
    output = highlighter.highlight_json(output)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsoncut\highlighter.py", line 53, in highlight_json
    return pygments.highlight(d, JsonLexer(), formatter)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\__init__.py", line 85, in highlight
    return format(lex(code, lexer), formatter, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\__init__.py", line 64, in format
    formatter.format(tokens, realoutfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatters\terminal.py", line 101, in format
    return Formatter.format(self, tokensource, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatter.py", line 95, in format
    return self.format_unencoded(tokensource, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatters\terminal.py", line 126, in format_unencoded
    outfile.write(ansiformat(color, line.rstrip('\n')))
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\console.py", line 68, in ansiformat
    result.append(codes[attr])
KeyError: 'darkgray'
</code>```

There is a guide for troubleshooting software in Anaconda: https://www.anaconda.com/what-to-do-when-things-go-wrong-in-anaconda/ but this is a brand-new install.

Does this look like an Anaconda issue, an issue with how I am running the software or an issue with the software itself?

答:
You're getting an error in site-packages with a module that is a dependency of something that you've installed.

Anaconda is just a distribtion, not the runtime.

The problem is from Python's pygments\console.py module, which is likely responsible for coloring the output of your jsonflatten module.

Try to see if there is a CLI flag to not colorize stuff, or don't use jsonflatten and rather use python's json.tool or separately install jq instead. (not saying those offer what you need, but they also parse JSON on the CLI)

Body:
New to programming. Installed Anaconda on a Windows 10 machine. Had some issues running updates.

While in Base environment, I installed my first Git repo successfully:

(base) C:\Users\samsung\Anaconda3\pkgs>pip install git+git://github.com/json-transformations/jsonflatten.git
Collecting git+git://github.com/json-transformations/jsonflatten.git
  Cloning git://github.com/json-transformations/jsonflatten.git to c:\users\samsung\appdata\local\temp\pip-req-build-zeiezw
  Running command git clone -q git://github.com/json-transformations/jsonflatten.git 'C:\Users\samsung\AppData\Local\Temp\p
Collecting jsoncut
  Downloading jsoncut-0.6-py2.py3-none-any.whl (17 kB)
Requirement already satisfied: click>=6.0 in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten==0.2) (7.0)
Requirement already satisfied: colorama in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten==0.2) (0
Requirement already satisfied: pygments in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten==0.2) (2
Building wheels for collected packages: jsonflatten
  Building wheel for jsonflatten (setup.py) ... done
  Created wheel for jsonflatten: filename=jsonflatten-0.2-py2.py3-none-any.whl size=8116 sha256=029aafde944303cbfe872e86a13
  Stored in directory: C:\Users\samsung\AppData\Local\Temp\pip-ephem-wheel-cache-so8173tt\wheels\8f\02\52\37295acfd1368a3d2
Successfully built jsonflatten
Installing collected packages: jsoncut, jsonflatten
Successfully installed jsoncut-0.6 jsonflatten-0.2

(base) C:\Users\samsung\Anaconda3\pkgs>pip install jsonflatten
Requirement already satisfied: jsonflatten in c:\users\samsung\anaconda3\lib\site-packages (0.2)
Requirement already satisfied: click>=6.0 in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten) (7.0)
Requirement already satisfied: jsoncut in c:\users\samsung\anaconda3\lib\site-packages (from jsonflatten) (0.6)
Requirement already satisfied: pygments in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten) (2.5.2)
Requirement already satisfied: colorama in c:\users\samsung\anaconda3\lib\site-packages (from jsoncut->jsonflatten) (0.4.3)

I then ran jsonflatten forecast.json as a test (as well as jsonflatten C:\Users\samsung.spyder-py3\forecast.json) as the readme suggests and got the output below. I ran from base as myenv (Python) spit out a message saying jsonflatten is not recognized as a command.

(base) C:\Users\samsung\.spyder-py3>jsonflatten C:\Users\samsung\.spyder-py3\forecast.json
Traceback (most recent call last):
  File "c:\users\samsung\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\samsung\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\samsung\Anaconda3\Scripts\jsonflatten.exe\__main__.py", line 7, in <module>
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 717, in main
    rv = self.invoke(ctx)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\click\decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsonflatten\cli.py", line 63, in main
    output(ctx, results, indent=4, is_json=True)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsoncut\cli.py", line 59, in output
    output = highlighter.highlight_json(output)
  File "c:\users\samsung\anaconda3\lib\site-packages\jsoncut\highlighter.py", line 53, in highlight_json
    return pygments.highlight(d, JsonLexer(), formatter)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\__init__.py", line 85, in highlight
    return format(lex(code, lexer), formatter, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\__init__.py", line 64, in format
    formatter.format(tokens, realoutfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatters\terminal.py", line 101, in format
    return Formatter.format(self, tokensource, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatter.py", line 95, in format
    return self.format_unencoded(tokensource, outfile)
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\formatters\terminal.py", line 126, in format_unencoded
    outfile.write(ansiformat(color, line.rstrip('\n')))
  File "c:\users\samsung\anaconda3\lib\site-packages\pygments\console.py", line 68, in ansiformat
    result.append(codes[attr])
KeyError: 'darkgray'

There is a guide for troubleshooting software in Anaconda: https://www.anaconda.com/what-to-do-when-things-go-wrong-in-anaconda/ but this is a brand-new install.

Does this look like an Anaconda issue, an issue with how I am running the software or an issue with the software itself?


问:
Adding Array from Variable on Google Sheets - Google Apps Script
I have an existing code which looks like,

```<code>var copyPageNumbers = [5, 7, 9];
</code>```

I have the same number 5, 7, 9 in a column on my google sheet and have set up a variable to get value,

```<code>var credentials = ss.getRange(i, 11).getValue(); // The value of this is 5, 7, 9
</code>```

Based on the variables above. I want to use a code which uses the credentials variable in the copyPageNumbers variable to look something like this,

```<code>var copyPageNumbers = [credentials];
</code>```

For example, the below chunk of code works,

```<code>  var credentials = ss.getRange(i, 11).getValue();
  var copyPageNumbers = [2, 4];

  var offset = 1;

  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });
</code>```

However when I try both the methods stated below - it doesnt work,

```<code>  var credentials = ss.getRange(i, 11).getValue().split(", ");
  var copyPageNumbers = credentials
  var offset = 1;
  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });
</code>```

```<code>  var credentials = ss.getRange(i, 11).getValue();
  var offset = 1;
  var copyPageNumbers = []
  copyPageNumbers.push(credentials);
  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });
</code>```

答:
Thanks to the above answers and thanks to Pattern 2 here, I have managed to solve this.

See updated script below. The reason it was not working before was because of the For each loop which was looping the slide and the number and the array was not working.

```<code>  var credentials = ss.getRange(i, 11).getValue().split(", ");

  var offset = 0;

  var slides_stack = otherPresentation.getSlides();
  var page = 0;

    credentials.forEach(function(p, i) {
    currentPresentation.insertSlide(offset + i, slides_stack[p - 1]);
  });
</code>```

Body:
I have an existing code which looks like,

var copyPageNumbers = [5, 7, 9];

I have the same number 5, 7, 9 in a column on my google sheet and have set up a variable to get value,

var credentials = ss.getRange(i, 11).getValue(); // The value of this is 5, 7, 9

Based on the variables above. I want to use a code which uses the credentials variable in the copyPageNumbers variable to look something like this,

var copyPageNumbers = [credentials];

For example, the below chunk of code works,

  var credentials = ss.getRange(i, 11).getValue();
  var copyPageNumbers = [2, 4];

  var offset = 1;

  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });

However when I try both the methods stated below - it doesnt work,

  var credentials = ss.getRange(i, 11).getValue().split(", ");
  var copyPageNumbers = credentials
  var offset = 1;
  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });

  var credentials = ss.getRange(i, 11).getValue();
  var offset = 1;
  var copyPageNumbers = []
  copyPageNumbers.push(credentials);
  var slides = otherPresentation.getSlides();
  var page = 0;
  slides.forEach(function(slide, i) {
    if (copyPageNumbers.indexOf(i + 1) != -1) {
      currentPresentation.insertSlide(offset + page, slide);
      page++;
    }
  });

Body:
Thanks to the above answers and thanks to Pattern 2 here, I have managed to solve this.

See updated script below. The reason it was not working before was because of the For each loop which was looping the slide and the number and the array was not working.

  var credentials = ss.getRange(i, 11).getValue().split(", ");

  var offset = 0;

  var slides_stack = otherPresentation.getSlides();
  var page = 0;

    credentials.forEach(function(p, i) {
    currentPresentation.insertSlide(offset + i, slides_stack[p - 1]);
  });