问:
Should I stop breaking .NET events guidelines?
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

```<code>// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}
</code>```

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!

答:
My design in this(and similar situations) usually differers for application and library code.

For reusable libraries I tend to follow the guidlines more, since that gives better versioning semantics. And changing the public api of a library is rather annoying.

In application code I tent to compromise more. Refactoring such an event handler used only in a single solution isn't that much work. So using your simplified pattern is OK IMO.

Body:
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!


来源: stackexchange

问:
Limit number of characters in input where jquery numpad is used
How would I limit number of characters in input where jquery keypad is used?

HTML

```<code><input id="num-input" type="text" maxlength="3" disabled>
</code>```

JQUERY

```<code>var $numInput;

$(function() {
  initKeyboard($('#numeric-keyboard'), $('#num-input'));

  $('#num-input').on('keydown', function(e) {
    $('#event').text('key: '+e.keyCode);
  });

  $('#back').on('click', onBackBtn);
  $('#forward').on('click', onForwardBtn);
});

function onBackBtn() {
   $('input').first().focus();
}

function onForwardBtn() {
   $('input').last().focus();
}

function initKeyboard($keyboard, $input) {
  $numInput = $input;

   $keyboard.on('click', '.key', onKeyPress);
}

function onKeyPress(e) {
  var keyValue = $(this).text();

  if(keyValue.toLowerCase() === 'delete') {
     keyValue = 8;
  } else if(keyValue === '') {
     return;
  } else {
     keyValue = keyValue.charCodeAt(0);
  }

  var e = $.Event("keydown");
  e.which = keyValue;
  e.keyCode = keyValue;

  $numInput.trigger(e);

  if(keyValue !== 8) {
    $numInput.val( $numInput.val() + $(this).text() );
  } else {
    $numInput.val( $numInput.val().slice(0, -1) );
  }
}
</code>```

maxlenght is ignorred, I attempted to add if clause to $numInput.val( $numInput.val() + $(this).text() ); this part of the code with var max=3; but again no luck.

I have also tried with out of this code script to limit number of characters for that input but again jquery overtakes it and keep adding characters.

I need t set limit of 3 characters to it.

Any idea?

答: #num-input is disabled, maybe maxlength need to be set in #numeric-keyboard field?

ContentLicense: CC BY-SA 4.0

Body:
How would I limit number of characters in input where jquery keypad is used?

HTML

<input id="num-input" type="text" maxlength="3" disabled>

JQUERY

var $numInput;

$(function() {
  initKeyboard($('#numeric-keyboard'), $('#num-input'));

  $('#num-input').on('keydown', function(e) {
    $('#event').text('key: '+e.keyCode);
  });

  $('#back').on('click', onBackBtn);
  $('#forward').on('click', onForwardBtn);
});

function onBackBtn() {
   $('input').first().focus();
}

function onForwardBtn() {
   $('input').last().focus();
}

function initKeyboard($keyboard, $input) {
  $numInput = $input;

   $keyboard.on('click', '.key', onKeyPress);
}

function onKeyPress(e) {
  var keyValue = $(this).text();

  if(keyValue.toLowerCase() === 'delete') {
     keyValue = 8;
  } else if(keyValue === '') {
     return;
  } else {
     keyValue = keyValue.charCodeAt(0);
  }

  var e = $.Event("keydown");
  e.which = keyValue;
  e.keyCode = keyValue;

  $numInput.trigger(e);

  if(keyValue !== 8) {
    $numInput.val( $numInput.val() + $(this).text() );
  } else {
    $numInput.val( $numInput.val().slice(0, -1) );
  }
}

maxlenght is ignorred, I attempted to add if clause to $numInput.val( $numInput.val() + $(this).text() ); this part of the code with var max=3; but again no luck.

I have also tried with out of this code script to limit number of characters for that input but again jquery overtakes it and keep adding characters.

I need t set limit of 3 characters to it.

Any idea?


问:
Junit test 5 (Exception)
I am doing a Junit test and in one of the tests I have problems but I don't understand why.

You do not have to allow more objects to be added to the list at any given time, that the size of the list is greater than 5, in short, if I add the sixth object to the list, the exception must be skipped, but I do not understand the reason why It does not work, I leave the code of what I am doing.

Code:

```<code> @Test
 void testAddTank() throws KeeperException, TankException {
  List<Tank> NumTanques = new ArrayList<Tank>();

  Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank7 = new Tank("TANQUE7","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

  NumTanques.add(tank1);
  NumTanques.add(tank2);
  NumTanques.add(tank3);
  NumTanques.add(tank4);
  NumTanques.add(tank5);

  assertEquals(5, NumTanques.size());

  KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
  assertEquals("[ERROR] A keeper cannot care of more than 5
  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);

}
</code>```

As you can see, I create the list of type tank and create some tank objects, which I add to the list. Then with the assert what I tell you is that 5 has to be the size of the list so that it returns true ...

Then in the exception that I create I add a new tank to the list and the exception should jump, but it does not, it exits and gives an error on the line:

```<code> KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
</code>```

I do not see clearly what is happening.

答:
I highly doubt that the Java class ArrayList throws an exception as you described it:

```<code>List<Tank> NumTanques = new ArrayList<Tank>();
</code>```

So if you want that Exception to be thrown you might need to use a custom class for that that keeps track of the added tanks and not use a plain ArrayList for that. Perhaps start by finding the code that actually throws an KeeperException.

Title: Junit test 5 (Exception)

Body:
I am doing a Junit test and in one of the tests I have problems but I don't understand why.

You do not have to allow more objects to be added to the list at any given time, that the size of the list is greater than 5, in short, if I add the sixth object to the list, the exception must be skipped, but I do not understand the reason why It does not work, I leave the code of what I am doing.

Code:

 @Test
 void testAddTank() throws KeeperException, TankException {
  List<Tank> NumTanques = new ArrayList<Tank>();

  Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank7 = new Tank("TANQUE7","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

  NumTanques.add(tank1);
  NumTanques.add(tank2);
  NumTanques.add(tank3);
  NumTanques.add(tank4);
  NumTanques.add(tank5);

  assertEquals(5, NumTanques.size());

  KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
  assertEquals("[ERROR] A keeper cannot care of more than 5
  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);

}

As you can see, I create the list of type tank and create some tank objects, which I add to the list. Then with the assert what I tell you is that 5 has to be the size of the list so that it returns true ...

Then in the exception that I create I add a new tank to the list and the exception should jump, but it does not, it exits and gives an error on the line:

 KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));

I do not see clearly what is happening.

Body:
I highly doubt that the Java class ArrayList throws an exception as you described it:

List<Tank> NumTanques = new ArrayList<Tank>();

So if you want that Exception to be thrown you might need to use a custom class for that that keeps track of the added tanks and not use a plain ArrayList for that. Perhaps start by finding the code that actually throws an KeeperException.


问:
How to limit width of multiple TextFields inside a Column? Wrapping the latter with a SizedBox doesn't work
This is my tree:

Scaffold(-> Column(-> Expanded(-> ListView(-> Column(-> TextFields)))));

I want to limit the width of these TextFields (say, to 200px), but using SizedBox/Container/ConstrainedBox and setting a width/maxWidth on the Column isn't working; I have to wrap each individual TextField with a SizedBox for it to work- which adds a lot of fluff to my code.

Is there a better way to do this?

答:
If you wrap your Column with a Container and set it to 200px, you'll not have to specify/wrap your TextFields individually anymore.

also looking at your hierarchy your Expanded widget will decide the max. width.

```<code>Scaffold(-> Column(-> Expanded(-> ListView(-> Container(width:200 -> Column(-> TextFields))))));

body: Container(
          width: 200,
          color: Colors.deepOrange,
          child: Column(
            children: [
              TextField(),
            ],
          ),
        ),
</code>```

Body:
If you wrap your Column with a Container and set it to 200px, you'll not have to specify/wrap your TextFields individually anymore.

also looking at your hierarchy your Expanded widget will decide the max. width.

Scaffold(-> Column(-> Expanded(-> ListView(-> Container(width:200 -> Column(-> TextFields))))));

body: Container(
          width: 200,
          color: Colors.deepOrange,
          child: Column(
            children: [
              TextField(),
            ],
          ),
        ),


问:
Get the array of objects from query parameters in javascript
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

```<code>http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom
</code>```

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

```<code>[{id:'21',name:'john'},{id:'22',name:'tom'}]
</code>```

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

```<code>export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</code>```

答:
I'll share my try:

var url = `http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom`;
var data = url.split('?')[1].split('&');

var result = Object.values(data.reduce((acc, elem)=>{
   key = elem.match(/\d+/)[0];
   kv = elem.split(".")[1].split('=');
   acc[key] = {...(acc[key] || []), ...{[kv[0]]:kv[1]}}
   return acc;
},{}));

console.log(result);```

Body:
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

[{id:'21',name:'john'},{id:'22',name:'tom'}]

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}


问:
Extract first element from multi dimensional array from pandas dataframe
I have a data frame consists of reviews column which is a multi dimensional array, I would like to extract first element as shown below,

Suppose df['Reviews'] consists of following rows

I want the output in a separate column as shown below,

Please find sample data 3 values for the column below:

df['Reviews'] =
[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']]
[['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']]
[['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]

Please help

答:
If need first lists use indexing by str[0]:

```<code>import ast

df['Reviews'] = df['Reviews'].apply(ast.literal_eval).str[0]
</code>```

If need join lists by , to strings add Series.str.join:

```<code>import ast

df['Reviews'] = df['Reviews'].apply(ast.literal_eval).str[0].str.join(',')
</code>```

Body:
If need first lists use indexing by str[0]:

import ast

df['Reviews'] = df['Reviews'].apply(ast.literal_eval).str[0]

If need join lists by , to strings add Series.str.join:

import ast

df['Reviews'] = df['Reviews'].apply(ast.literal_eval).str[0].str.join(',')


问:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException JavaFX FXML
I have several fxml files with corresponding control files. They all work except one. That one used to work. Here is the error log. I am using Netbeans 12.0 beta 2 and Maven. I am also using Scenebuilder. I am using 6 major fxml files. All of them work except browse.fxml.

```<code>Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.mycompany.kioskapp2.App.loadFXML(App.java:34)
    at com.mycompany.kioskapp2.App.setRoot(App.java:29)
    at com.mycompany.kioskapp2.PrimaryController.BrowseItemsButtonAction(PrimaryController.java:24)
</code>```

browse.fxml

App.java

public class App extends Application {

    private static Scene scene;
    public static String Username, Password;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("primary"), 800, 700);
        stage.setTitle("Grogan Vending");
        stage.setScene(scene);
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        System.out.println("in setRoot");
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    @SuppressWarnings("empty-statement")
    public static void VerifyUsername(String user, String passwd) throws IOException {
        System.out.println("in App.VerifyUsername");
        Boolean bool1 = false;
        Boolean bool2 = false;
        Boolean found1 = false;
        Boolean found2 = false;
        String savestr = null;
        try {
            try (FileReader reader = new FileReader("C:\\Users\\Skibum.DESKTOP-DBDQH1D\\Documents\\NetBeansProjects\\KioskApp2\\src\\main\\resources\\com\\mycompany\\kioskapp2\\LoginFile.txt")) {
                BufferedReader bufferedReader = new BufferedReader(reader);

                String dbline;

                while ((dbline = bufferedReader.readLine()) != null) {
                    bool1 = dbline.contains(user);
                    if (bool1 == true) {
                        found1 = true;
                        found2 = dbline.contains(passwd);
                        savestr = dbline;
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (found2 == false) {
            App.setRoot("passwderr");
        }
        if (found1 == false) {
            try {
                App.setRoot("usernameerr");
            } catch (IOException ex) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (found1 == true && found2 == true) {
            String result[] = savestr.split(",");
            for (String temp: result){

            }
            System.out.println(result[2]);
            App.setRoot("primary");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
```

<p>PrimaryController.java</p>

<pre class="lang-java prettyprint-override"><code>public class PrimaryController {

    @FXML private Text actiontarget;

    @FXML private void LoginButtonAction() throws IOException {
        App.setRoot("login");
        System.out.println("Login button pressed");
    }

    @FXML private void NewAccountButtonAction() throws IOException {
        App.setRoot("newaccount");
        System.out.println("New Account button pressed");
    }

    @FXML private void BrowseItemsButtonAction() throws IOException {
        App.setRoot("browse");
        System.out.println("Browse Items button pressed");
    }

    @FXML private void ExpenseAcctButtonAction()throws IOException {
        App.setRoot("expenseacct");
        System.out.println("expense acct button pressed");
    }

    @FXML private void HelpButtonAction()throws IOException {
        App.setRoot("help");
        System.out.println("Help button pressed");
    }

    @FXML private void SuggestButtonAction()throws IOException {
        App.setRoot("suggestions");
        System.out.println("Suggestions button pressed");
    }

}
</code>```

Stack Trace

```<code>    Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
    Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 48 more
    Caused by: javafx.fxml.LoadException:
    /C:/Users/Skibum.DESKTOP-DBDQH1D/Documents/NetBeansProjects/KioskApp2/target/classes/com/mycompany/kioskapp2/browse.fxml:16

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at com.mycompany.kioskapp2.App.loadFXML(App.java:34)
at com.mycompany.kioskapp2.App.setRoot(App.java:29)
at com.mycompany.kioskapp2.PrimaryController.BrowseItemsButtonAction(PrimaryController.java:24)
... 58 more
    Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
... 68 more
</code>```

答:
You are missing the event type is the function's parameters

```<code>BrowseItemsButtonAction()
</code>```

should be

```<code>BrowseItemsButtonAction(MouseEvent event)
</code>```

Body:
I have several fxml files with corresponding control files. They all work except one. That one used to work. Here is the error log. I am using Netbeans 12.0 beta 2 and Maven. I am also using Scenebuilder. I am using 6 major fxml files. All of them work except browse.fxml.

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.mycompany.kioskapp2.App.loadFXML(App.java:34)
    at com.mycompany.kioskapp2.App.setRoot(App.java:29)
    at com.mycompany.kioskapp2.PrimaryController.BrowseItemsButtonAction(PrimaryController.java:24)

browse.fxml

App.java

public class App extends Application {

    private static Scene scene;
    public static String Username, Password;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("primary"), 800, 700);
        stage.setTitle("Grogan Vending");
        stage.setScene(scene);
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        System.out.println("in setRoot");
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    @SuppressWarnings("empty-statement")
    public static void VerifyUsername(String user, String passwd) throws IOException {
        System.out.println("in App.VerifyUsername");
        Boolean bool1 = false;
        Boolean bool2 = false;
        Boolean found1 = false;
        Boolean found2 = false;
        String savestr = null;
        try {
            try (FileReader reader = new FileReader("C:\\Users\\Skibum.DESKTOP-DBDQH1D\\Documents\\NetBeansProjects\\KioskApp2\\src\\main\\resources\\com\\mycompany\\kioskapp2\\LoginFile.txt")) {
                BufferedReader bufferedReader = new BufferedReader(reader);

                String dbline;

                while ((dbline = bufferedReader.readLine()) != null) {
                    bool1 = dbline.contains(user);
                    if (bool1 == true) {
                        found1 = true;
                        found2 = dbline.contains(passwd);
                        savestr = dbline;
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (found2 == false) {
            App.setRoot("passwderr");
        }
        if (found1 == false) {
            try {
                App.setRoot("usernameerr");
            } catch (IOException ex) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (found1 == true && found2 == true) {
            String result[] = savestr.split(",");
            for (String temp: result){

            }
            System.out.println(result[2]);
            App.setRoot("primary");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

PrimaryController.java

public class PrimaryController {

    @FXML private Text actiontarget;

    @FXML private void LoginButtonAction() throws IOException {
        App.setRoot("login");
        System.out.println("Login button pressed");
    }

    @FXML private void NewAccountButtonAction() throws IOException {
        App.setRoot("newaccount");
        System.out.println("New Account button pressed");
    }

    @FXML private void BrowseItemsButtonAction() throws IOException {
        App.setRoot("browse");
        System.out.println("Browse Items button pressed");
    }

    @FXML private void ExpenseAcctButtonAction()throws IOException {
        App.setRoot("expenseacct");
        System.out.println("expense acct button pressed");
    }

    @FXML private void HelpButtonAction()throws IOException {
        App.setRoot("help");
        System.out.println("Help button pressed");
    }

    @FXML private void SuggestButtonAction()throws IOException {
        App.setRoot("suggestions");
        System.out.println("Suggestions button pressed");
    }

}

Stack Trace

    Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
    Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 48 more
    Caused by: javafx.fxml.LoadException:
    /C:/Users/Skibum.DESKTOP-DBDQH1D/Documents/NetBeansProjects/KioskApp2/target/classes/com/mycompany/kioskapp2/browse.fxml:16

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at com.mycompany.kioskapp2.App.loadFXML(App.java:34)
at com.mycompany.kioskapp2.App.setRoot(App.java:29)
at com.mycompany.kioskapp2.PrimaryController.BrowseItemsButtonAction(PrimaryController.java:24)
... 58 more
    Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
... 68 more

Body:
You are missing the event type is the function's parameters

BrowseItemsButtonAction()

should be

BrowseItemsButtonAction(MouseEvent event)


问:
Passing data from a class which is Lifecycle observer to the Activity
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

```<code>class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }
</code>```

I am Calling this class from MainActivity onCreate method like this

```<code>BatteryInfo(this, lifecycle)
</code>```

答:
I know its not you answer but its a different approach of getting things done. It also removes all of your boilerplate code.

You can use an object to extract all your data from intent and return an instance of your data class.
Read more about object in kotlin here - https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html

```<code>object BatteryInfoUtils {

      fun getBatteryInfoFromIntent(intent: Intent): Stats { intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  return Stats(level, temperature, voltage, technology, plugged, health)
                }
}
</code>```

And inside MainActivity onCreate()

```<code> override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)

     val stats = getBatteryInfo()

 }

fun getBatteryInfo(): Stats? {
 var stats: Stats? = null
 val intent: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
                registerReceiver(null, ifilter)
            }
 intent?.let { batteryIntent ->
                stats = BatteryInfoUtils.getBatteryInfoFromIntent(batteryIntent)
  }
 return stats
}
</code>```

Body:
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }

I am Calling this class from MainActivity onCreate method like this

BatteryInfo(this, lifecycle)

Body:
I know its not you answer but its a different approach of getting things done. It also removes all of your boilerplate code.

You can use an object to extract all your data from intent and return an instance of your data class.
Read more about object in kotlin here - https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html

object BatteryInfoUtils {

      fun getBatteryInfoFromIntent(intent: Intent): Stats { intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  return Stats(level, temperature, voltage, technology, plugged, health)
                }
}

And inside MainActivity onCreate()

 override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)

     val stats = getBatteryInfo()

 }

fun getBatteryInfo(): Stats? {
 var stats: Stats? = null
 val intent: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
                registerReceiver(null, ifilter)
            }
 intent?.let { batteryIntent ->
                stats = BatteryInfoUtils.getBatteryInfoFromIntent(batteryIntent)
  }
 return stats
}


问:
Non readable/editable file format for script files in Linux
I have written a script in a linux machine using python.
 Is there a way to convert .py script file into non readable format such as .exe in windows.
Let me know your answers please.

答: visit pyinstaller which provides you the tools to create such file.</p>


问:
Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64
I'd like to install the pymongo library but I'm getting the following error:

```<code>    (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda install -c anaconda pymongo

    Fetching package metadata ...
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a
    naconda/win-64/repodata.json>
    Elapsed: -

    An HTTP error occurred when trying to retrieve this URL.
    HTTP errors are often intermittent, and a simple retry will get you on your way.

    ConnectTimeout(MaxRetryError("HTTPSConnectionPool(host='conda.anaconda.org', por
    t=443): Max retries exceeded with url: /anaconda/win-64/repodata.json (Caused by
     ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000
    00000054D6128>, 'Connection to conda.anaconda.org timed out. (connect timeout=9.
    15)'))",),)
</code>```

Steps taken to resolve:

```<code>1. Update C:\Users\\xxxxxxx\.condarc file with the following:

channels:
  - defaults
ssl_verify: false
proxy_servers:
http: http://sproxy.fg.xxx.com:1000
https: https://sproxy.fg.xxx.com:1000

2. (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda config --set ssl_verify False
</code>```

Additional Info:

```<code>(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda info

Current conda install:

               platform : win-64
          conda version : 4.3.27
       conda is private : False
      conda-env version : 4.3.27
    conda-build version : 3.0.22
         python version : 3.6.2.final.0
       requests version : 2.18.4
            config file : C:\Users\xxxxxxx\.condarc
             netrc file : None
           offline mode : False
             user-agent : conda/4.3.27 requests/2.18.4 CPython/3.6.2 Windows/7 W
indows/6.1.7601
          administrator : False
</code>```

A number of posts online simply reinstalled Anaconda, any other options apart from a fresh install?

答:
I faced this issue when I tried to create environment. I solved it by first activating conda base environment by using:

```<code>conda activate base
</code>```

then I created the environment

```<code>conda create -n myenv python=3.7
</code>```

Body:
I'd like to install the pymongo library but I'm getting the following error:

    (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda install -c anaconda pymongo

    Fetching package metadata ...
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a
    naconda/win-64/repodata.json>
    Elapsed: -

    An HTTP error occurred when trying to retrieve this URL.
    HTTP errors are often intermittent, and a simple retry will get you on your way.

    ConnectTimeout(MaxRetryError("HTTPSConnectionPool(host='conda.anaconda.org', por
    t=443): Max retries exceeded with url: /anaconda/win-64/repodata.json (Caused by
     ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000
    00000054D6128>, 'Connection to conda.anaconda.org timed out. (connect timeout=9.
    15)'))",),)

Steps taken to resolve:

1. Update C:\Users\\xxxxxxx\.condarc file with the following:

channels:
  - defaults
ssl_verify: false
proxy_servers:
http: http://sproxy.fg.xxx.com:1000
https: https://sproxy.fg.xxx.com:1000

2. (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda config --set ssl_verify False

Additional Info:

(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda info

Current conda install:

               platform : win-64
          conda version : 4.3.27
       conda is private : False
      conda-env version : 4.3.27
    conda-build version : 3.0.22
         python version : 3.6.2.final.0
       requests version : 2.18.4
            config file : C:\Users\xxxxxxx\.condarc
             netrc file : None
           offline mode : False
             user-agent : conda/4.3.27 requests/2.18.4 CPython/3.6.2 Windows/7 W
indows/6.1.7601
          administrator : False

A number of posts online simply reinstalled Anaconda, any other options apart from a fresh install?

Body:
I faced this issue when I tried to create environment. I solved it by first activating conda base environment by using:

conda activate base

then I created the environment

conda create -n myenv python=3.7


问:
I am updating Angular version from 7 to 8. But getting peer dependency error
I tried using --force , but of no use.

enter image description here

error code -

```<code>    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").
</code>```

答:
you need to install the compatible version of each dependency here's the code for that </p>

```<code>npm i --save dependencyName@version
</code>```

Body:
I tried using --force , but of no use.

enter image description here

error code -

    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").

Body:
you need to install the compatible version of each dependency here's the code for that

npm i --save dependencyName@version


问:
Android Market- Number of Active installs exceeds total downloads

I am wondering how the active installs exceeds the total installs. I suspect some one copied the app and installed on another phone...Can anyone post if it is possible some other way?

答:
The market statistics are by no means perfect.  They are only periodically updated, and have frequently bounced around like crazy.  When I first published an app it was actually double counting one of the stats - Google fixed the bug that caused that but didn't fix the statistics.

I've also seen people report issues with paid application statistics being inaccurate where people click to buy and the download doesn't go through, or they cancel inside the 15 min window etc..

They constantly tweek the basis for the calculation as well - with a change as recent as May 2nd

As of May 2, 2011, we’ve changed the
  basis for calculation of install
  numbers provided in the Android Market
  Developer Console. Previously, app
  installs were calculated per user and
  did not account for certain uninstall
  activities (like when a device was
  factory reset). Installs are now
  counted per device, with duplicates
  more effectively filtered out. This
  offers you a more accurate measure of
  your app distribution in the Android
  ecosystem.

You may notice that this change has
  resulted in a one-time decrease in the
  number of total installs for your
  apps. We apologize for any confusion
  this may have caused

Basically there a lots of bugs with the way they track the stats so don't trust 'em.

ContentLicense: CC BY-SA 3.0


Title: grouping datatable based on uptrend, downtrend and range in R

Body:
I have a data table like this :

timestamp           Value
05-01-2020  12:07:08    8
05-01-2020  12:36:05    9
05-01-2020  23:45:02    10.3
05-01-2020  13:44:33    11
06-01-2020  01:07:08    12.5
06-01-2020  10:23:05    11.3
06-01-2020  12:11:08    10.8
06-01-2020  22:06:12    9.7
07-01-2020  00:01:05    9.3
07-01-2020  02:17:09    8.6
07-01-2020  12:36:05    8.3
07-01-2020  12:07:08    7.8
07-01-2020  12:36:05    8.7
07-01-2020  12:36:05    9.3
08-01-2020  12:36:05    9.8
08-01-2020  12:36:05    10.4
08-01-2020  12:36:05    10.5
09-01-2020  12:36:05    10.3
09-01-2020  12:07:08    9.6
09-01-2020  12:36:05    9.1
11-01-2020  12:07:08    8.8
11-01-2020  12:36:05    8.3

I am trying to create three groups G1,G2,G3
G1 is for uptrend(increasing order) for values 9 to 12 - Both values included,
G2 is for downtrend(decreasing order) for values 12 to 9  - Both values included,
G3 is for range of values between 9 and 12  - Both values included.

Grouping should be per day basis.

I am able to get G3. But other conditions are not working.

df[, G3 := rleid((value >= 9  & value <=12)  & (as.IDate(timestamp) == shift(as.Idate(timestamp),type ='lag'))]

Desired output :

timestamp              Value    G1  G2  G3
05-01-2020  12:07:08    8        1  1   1
05-01-2020  12:36:05    9        2  1   2
05-01-2020  23:45:02    10.3     2  1   2
05-01-2020  13:44:33    11       2  1   2
06-01-2020  01:07:08    12.5     3  1   3
06-01-2020  10:23:05    11.3     4  2   4
06-01-2020  12:11:08    10.8     4  2   4
06-01-2020  22:06:12    9.7      4  2   4
07-01-2020  00:01:05    9.3      5  3   5
07-01-2020  02:17:09    8.6      6  4   6
07-01-2020  12:36:05    8.3      6  4   6
07-01-2020  12:07:08    7.8      6  4   6
07-01-2020  12:36:05    8.7      6  4   6
07-01-2020  12:36:05    9.3      7  4   7
08-01-2020  12:36:05    9.8      8  4   8
08-01-2020  12:36:05    10.4     8  4   8
08-01-2020  12:36:05    10.5     8  4   8
09-01-2020  12:36:05    10.3     9  5   8
09-01-2020  12:07:08    9.6      9  5   9
09-01-2020  12:36:05    9.1      9  5   9
11-01-2020  12:07:08    8.8      9  6   10
11-01-2020  12:36:05    8.3      9  6   10

Body:
Here is a possible answer to this interesting question.

It is difficult to judge if this answer is correct as the expected result posted in the question seems to be inconsistent even with OP's own rule set and with OP's own code (e.g., some day changes are not accounted for).

library(data.table)
setDT(df)[, Date := as.IDate(timestamp, "%d-%m-%Y")]
df[, Change := nafill(c(diff(Value), NA), "locf"), by = Date]
df[, `:=`(
  G1 = rleid(Date, between(Value, 9, 12) & Change > 0),
  G2 = rleid(Date, between(Value, 9, 12) & Change < 0),
  G3 = rleid(Date, between(Value, 9, 12)),
  Date = NULL,
  Change = NULL
)][]

              timestamp Value G1 G2 G3
 1: 05-01-2020 12:07:08   8.0  1  1  1
 2: 05-01-2020 12:36:05   9.0  2  1  2
 3: 05-01-2020 23:45:02  10.3  2  1  2
 4: 05-01-2020 13:44:33  11.0  2  1  2
 5: 06-01-2020 01:07:08  12.5  3  2  3
 6: 06-01-2020 10:23:05  11.3  3  3  4
 7: 06-01-2020 12:11:08  10.8  3  3  4
 8: 06-01-2020 22:06:12   9.7  3  3  4
 9: 07-01-2020 00:01:05   9.3  4  4  5
10: 07-01-2020 02:17:09   8.6  4  5  6
11: 07-01-2020 12:36:05   8.3  4  5  6
12: 07-01-2020 12:07:08   7.8  4  5  6
13: 07-01-2020 12:36:05   8.7  4  5  6
14: 07-01-2020 12:36:05   9.3  5  5  7
15: 08-01-2020 12:36:05   9.8  6  6  8
16: 08-01-2020 12:36:05  10.4  6  6  8
17: 08-01-2020 12:36:05  10.5  6  6  8
18: 09-01-2020 12:36:05  10.3  7  7  9
19: 09-01-2020 12:07:08   9.6  7  7  9
20: 09-01-2020 12:36:05   9.1  7  7  9
21: 11-01-2020 12:07:08   8.8  8  8 10
22: 11-01-2020 12:36:05   8.3  8  8 10
              timestamp Value G1 G2 G3

Data

library(data.table)
df <- fread(
  "timestamp  time         Value
05-01-2020  12:07:08    8
05-01-2020  12:36:05    9
05-01-2020  23:45:02    10.3
05-01-2020  13:44:33    11
06-01-2020  01:07:08    12.5
06-01-2020  10:23:05    11.3
06-01-2020  12:11:08    10.8
06-01-2020  22:06:12    9.7
07-01-2020  00:01:05    9.3
07-01-2020  02:17:09    8.6
07-01-2020  12:36:05    8.3
07-01-2020  12:07:08    7.8
07-01-2020  12:36:05    8.7
07-01-2020  12:36:05    9.3
08-01-2020  12:36:05    9.8
08-01-2020  12:36:05    10.4
08-01-2020  12:36:05    10.5
09-01-2020  12:36:05    10.3
09-01-2020  12:07:08    9.6
09-01-2020  12:36:05    9.1
11-01-2020  12:07:08    8.8
11-01-2020  12:36:05    8.3")[
  , `:=`(timestamp = paste(timestamp, time), time = NULL)]


问:
Saving Google Sheets as xlsx file and manipulating with loses .gs scripts written
I have a lot of Google Sheet files that have some .gs scripts in them. I wanted to change them in mass using a Python script and downloaded them all and ran the Python script to do the changes.

After it's all done, I realized that downloading the Google Sheets somehow loses the .gs scripts that are tied to the file (I think because Google Sheets and xlsx files are different and somehow xlsx doesn't support .gs scripts). Is there any way that I can run my Python script on those Google Sheets without losing the .gs scripts?

P.S: Don't ask my why use both Python scripts and .gs scripts :)

答:
Consideration

The .xlsx file you can download from Google APIs won't contain the bound Google Apps Script file. The script files are separate entities from their containers even though they are related.

Solution

You can use the Google Apps Script API with Python to manage your Apps Script Projects. In order to do so you will need the Scripts Ids.

To retrieve the Script Ids of a bound Google Apps Script file you will have to use the Apps Script method .getScriptId(). In this case I suggest to create an Apps Script standalone projects that retrieves the Script Ids and saves them so you can use them with your Python script.

Once you have all the Script Ids you can adapt your Python script to perform the changes.

References

.getScriptId()

Get Apps Script Projects

Get Apps Script Projects Content

Update Apps Script Projects


问:
Replace static array of objects with GraphQL queried data
I have static data in my React app in a file called tags.js as follows:

```<code>const tagsArray = [
  {
    id: 1,
    label: "test1"
  },
  {
    id: 2,
    label: "test2"
  }]
</code>```

I import this into my index.js file and use it in my App.

```<code>import tagsArray from "./tags";

ReactDOM.render(
<App data={tagsArray} />
document.getElementById("root")
);
</code>```

I have a remote GraphQL service containing updated data and want to use a query to pull the array of objects and replace the static tagsArray.

I can successfully query the GraphQL data with this function:

```<code>function GQLTagFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.tag.map(({ id, label }) => (
    <div key={id}>
      id:{id}, label:{label}
    </div>
  ));
}
</code>```

Which returns:

```<code>id:1, label:"test1"
id:2, label:"test2"
</code>```

I know this format is incorrect but I'm not sure how to modify the function to map the data to the same format (array of objects) as tagsArray and then assign it to a variable called queriedTagsArray so I could use it in my app as follows:

<App data={queriedTagsArray} />

答:
You need to wrap entire, existing App into Apollo provider and your querying component.

To keep naming conventions:

rename your existing App to WrappedApp,

create a new <App/> component with Apollo initialization and rendering ApolloProvider' and your query component (  ` ),

in index.js just ReactDOM.render( <App/>, document.getElementById("root") );

Use new name of App (WrappedApp) in GQLTagFunc:

```<code>function GQLTagFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return <WrappedApp data={data.tag} />;
}
</code>```

Hint

If this is your only graphql querying then you don't need [big] Apollo at all - you can use fetch/axios to read json data.

Body:
I have static data in my React app in a file called tags.js as follows:

const tagsArray = [
  {
    id: 1,
    label: "test1"
  },
  {
    id: 2,
    label: "test2"
  }]

I import this into my index.js file and use it in my App.

import tagsArray from "./tags";

ReactDOM.render(
<App data={tagsArray} />
document.getElementById("root")
);

I have a remote GraphQL service containing updated data and want to use a query to pull the array of objects and replace the static tagsArray.

I can successfully query the GraphQL data with this function:

function GQLTagFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return
Loading...
;
  if (error) return
Error :(
;

  return data.tag.map(({ id, label }) => (

      id:{id}, label:{label}

  ));
}

Which returns:

id:1, label:"test1"
id:2, label:"test2"

I know this format is incorrect but I'm not sure how to modify the function to map the data to the same format (array of objects) as tagsArray and then assign it to a variable called queriedTagsArray so I could use it in my app as follows:

<App data={queriedTagsArray} />

Body:
You need to wrap entire, existing App into Apollo provider and your querying component.

To keep naming conventions:

rename your existing App to WrappedApp,

create a new <App/> component with Apollo initialization and rendering ApolloProvider' and your query component (  ` ),

in index.js just ReactDOM.render( <App/>, document.getElementById("root") );

Use new name of App (WrappedApp) in GQLTagFunc:

function GQLTagFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return <WrappedApp data={data.tag} />;
}

Hint

If this is your only graphql querying then you don't need [big] Apollo at all - you can use fetch/axios to read json data.


问:
Android - Check the certificate of an app
Hi

Is there any way to check the certificate of an app (e.g. Amazon Mobile)?

decompile the apk or whatever?

Thanks

答:
You can use the jarsigner tool from JDK.

JDKFOLDER\bin\jarsigner.exe -verify -verbose -certs myAndroidProgram.apk


问:
Can't install localstack on freshly reformatted ubuntu 18.04?
I'm having a hard time installing localstack. This is on a freshly reformatted ubuntu pc. I keep getting this error:

```<code>(test which virtualenv || pip install --user virtualenv) &&
(test -e .venv || virtualenv .venv) &&
(test ! -e requirements.txt || (. .venv/bin/activate; pip -q install -r requirements.txt) &&
. .venv/bin/activate; PYTHONPATH=. exec python localstack/services/install.py testlibs)
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7910>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7b90>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7cd0>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7e10>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7f50>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Could not find a version that satisfies the requirement airspeed==0.5.5.dev20160812 (from -r requirements.txt (line 4)) (from versions: )
No matching distribution found for airspeed==0.5.5.dev20160812 (from -r requirements.txt (line 4))
</code>```

Anyone got a solution for this?

答:
As I can see you are trying to run

```<code>$> localstack start
</code>```

which required docker and docker-compose.

To run natively, you need to use:

```<code>$> localstack start --host
</code>```

I have written step by step blogs to install and run natively. You can refer : https://medium.com/@baksh12shad/how-to-install-localstack-natively-on-ubuntu-18-04-step-by-step-ca344b7b7d78

Body:
I'm having a hard time installing localstack. This is on a freshly reformatted ubuntu pc. I keep getting this error:

(test which virtualenv || pip install --user virtualenv) &&
(test -e .venv || virtualenv .venv) &&
(test ! -e requirements.txt || (. .venv/bin/activate; pip -q install -r requirements.txt) &&
. .venv/bin/activate; PYTHONPATH=. exec python localstack/services/install.py testlibs)
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7910>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7b90>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7cd0>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7e10>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f13119c7f50>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/airspeed/
Could not find a version that satisfies the requirement airspeed==0.5.5.dev20160812 (from -r requirements.txt (line 4)) (from versions: )
No matching distribution found for airspeed==0.5.5.dev20160812 (from -r requirements.txt (line 4))

Anyone got a solution for this?

Body:
As I can see you are trying to run

$> localstack start

which required docker and docker-compose.

To run natively, you need to use:

$> localstack start --host

I have written step by step blogs to install and run natively. You can refer : https://medium.com/@baksh12shad/how-to-install-localstack-natively-on-ubuntu-18-04-step-by-step-ca344b7b7d78


问:
How to get file count of a particular extension in Go?
I am using ioutil for iterating a folder:

existingFiles, err := ioutil.ReadDir(indexPath)
```

I want to get the count of files if they are of type .txt. How can I do that without looping? is there any way to pass the pattern?

答:
You can use filepath.Glob():

```<code>pattern := filepath.Join(indexPath, "*.txt")
files, err := filepath.Glob(pattern)
if err == nil {
    fmt.Printf("Found %d files.\n", len(files))
}
</code>```

Body:
I am using ioutil for iterating a folder:

existingFiles, err := ioutil.ReadDir(indexPath)

I want to get the count of files if they are of type .txt. How can I do that without looping? is there any way to pass the pattern?

Body:
You can use filepath.Glob():

pattern := filepath.Join(indexPath, "*.txt")
files, err := filepath.Glob(pattern)
if err == nil {
    fmt.Printf("Found %d files.\n", len(files))
}


问:
Better way to apply function to every combination of two columns in Pandas.DataFrame
I want to implement a something just like DataFrame.corr() which can apply a function to pairwise columns.
Eg.
I have a function:

```<code>def func(x, y):
    pass
</code>```

I want to apply func to every combination of two columns in a_pd(type of Pandas.DataFrame). I have figured out a way by create a new function wap_func to wrap func:

```<code>def wap_func(x):
    for i in range(len(x)):
        for j in range(i+1, len(x)):
            func(x[i], x[j])

res = a_pd.apply(wap_func, axis=1)
</code>```

Although the question seems to be solved, but it isn't convenient. If it could be done like a_pd.corr(), it could be better.

答:
Have you considered using the itertools.combinations module?

import pandas as pd
from itertools import combinations

df = pd.DataFrame([[1,2,3], [2,3,4], [3,5,7]], columns = ['A', 'B', 'C'])
print(df)

   A  B  C
0  1  2  3
1  2  3  4
2  3  5  7
```

<p>Define your function slightly differently so that you can use apply more seamlessly</p>

<pre class="lang-py prettyprint-override"><code>def func(xy):
    x, y = xy
    return x+y
</code>```

Use the itertools.combinations module to get all combinations of the columns that you wish, go through each of the combinations in turn, and apply the function earlier defined

for combi in combinations(df.columns, 2):
    df['_'.join([i for i in combi])] = df[[i for i in combi]].apply(func, axis=1, result_type='expand').transpose().values

print(df)

   A  B  C  A_B  A_C  B_C
0  1  2  3    3    4    5
1  2  3  4    5    6    7
2  3  5  7    8   10   12
```

Body:
I want to implement a something just like DataFrame.corr() which can apply a function to pairwise columns.
Eg.
I have a function:

def func(x, y):
    pass

I want to apply func to every combination of two columns in a_pd(type of Pandas.DataFrame). I have figured out a way by create a new function wap_func to wrap func:

def wap_func(x):
    for i in range(len(x)):
        for j in range(i+1, len(x)):
            func(x[i], x[j])

res = a_pd.apply(wap_func, axis=1)

Although the question seems to be solved, but it isn't convenient. If it could be done like a_pd.corr(), it could be better.

Body:
Have you considered using the itertools.combinations module?

import pandas as pd
from itertools import combinations

df = pd.DataFrame([[1,2,3], [2,3,4], [3,5,7]], columns = ['A', 'B', 'C'])
print(df)

   A  B  C
0  1  2  3
1  2  3  4
2  3  5  7

Define your function slightly differently so that you can use apply more seamlessly

def func(xy):
    x, y = xy
    return x+y

Use the itertools.combinations module to get all combinations of the columns that you wish, go through each of the combinations in turn, and apply the function earlier defined

for combi in combinations(df.columns, 2):
    df['_'.join([i for i in combi])] = df[[i for i in combi]].apply(func, axis=1, result_type='expand').transpose().values

print(df)

   A  B  C  A_B  A_C  B_C
0  1  2  3    3    4    5
1  2  3  4    5    6    7
2  3  5  7    8   10   12


问:
Angular : Can't export excel using ExcelJS - error TS2307: Cannot find module 'stream' - error TS2503: Cannot find namespace 'NodeJS'
I was try to export an excel file using ExcelJS

Here is my console in VS Code terminal :

```<code>ERROR in node_modules/exceljs/index.d.ts:1398:22 - error TS2307: Cannot find module 'stream'.

1398  read(stream: import('stream').Stream): Promise<Workbook>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1424:23 - error TS2307: Cannot find module 'stream'.

1424  write(stream: import('stream').Stream, options?: Partial<XlsxWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1511:22 - error TS2307: Cannot find module 'stream'.

1511  read(stream: import('stream').Stream, options?: Partial<CsvReadOptions>): Promise<Worksheet>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1531:23 - error TS2307: Cannot find module 'stream'.

1531  write(stream: import('stream').Stream, options?: Partial<CsvWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1828:19 - error TS2307: Cannot find module 'stream'.

1828            stream: import('stream').Stream;
                               ~~~~~~~~
node_modules/exceljs/index.d.ts:1872:34 - error TS2503: Cannot find namespace 'NodeJS'.

1872             dictionary: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default                                      ~~~~~~
</code>```

here is app.component.html

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> -->

  <!-- serial must : first jquery then popper then bootstrap -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> -->

</head>

<body>

    <div class="row">

      <div class="col-md-2">
        <button class="btn btn-secondary" (click)='downloadExcel()'>Download as Excel</button>
      </div>

    </div>

</body>

</html>
</code>```

here is app.component.ts

```<code>import { Component } from '@angular/core';
import * as Excel from 'exceljs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'resttest10';

  async downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];

    worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

    // save under export.xlsx
    await workbook.xlsx.writeFile('export.xlsx');

    // load a copy of export.xlsx
    const newWorkbook = new Excel.Workbook();
    await newWorkbook.xlsx.readFile('export.xlsx');

    const newworksheet = newWorkbook.getWorksheet('My Sheet');
    newworksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];
    await newworksheet.addRow({ id: 3, name: 'New Guy', dob: new Date(2000, 1, 1) });

    await newWorkbook.xlsx.writeFile('export2.xlsx');

    console.log('File is written');
  }
}
</code>```

I don't get it why it is looking for stream module (and more funny thing - Cannot find namespace 'NodeJS' - I can run all other angular NodeJS projects without error)

Please point out why i can't export excel.

答:
You can't write directly a file on client side. that method is mean to be used on backend side in nodejs. if your expectation is download this file on client side. your code should be like :- </p>

```<code>import { Component } from "@angular/core";
import * as Excel from "exceljs";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "resttest10";

  async downloadExcel() {
    const date = new Date()
      .toISOString()
      .slice(0, 10)
      .split("-")
      .reverse()
      .join("/");
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet("My Sheet");

    worksheet.columns = [
      { header: "Id", key: "id", width: 10 },
      { header: "Name", key: "name", width: 32 },
      { header: "D.O.B.", key: "dob", width: 15 }
    ];

    worksheet.addRow({ id: 1, name: "John Doe", dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: "Jane Doe", dob: new Date(1965, 1, 7) });

    workbook.xlsx.writeBuffer().then((data: any) => {
      console.log("buffer");
      const blob = new Blob([data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      document.body.appendChild(a);
      a.setAttribute("style", "display: none");
      a.href = url;
      a.download = "export.xlsx";
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    });
  }
}
</code>```

Body:
I was try to export an excel file using ExcelJS

Here is my console in VS Code terminal :

ERROR in node_modules/exceljs/index.d.ts:1398:22 - error TS2307: Cannot find module 'stream'.

1398  read(stream: import('stream').Stream): Promise<Workbook>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1424:23 - error TS2307: Cannot find module 'stream'.

1424  write(stream: import('stream').Stream, options?: Partial<XlsxWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1511:22 - error TS2307: Cannot find module 'stream'.

1511  read(stream: import('stream').Stream, options?: Partial<CsvReadOptions>): Promise<Worksheet>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1531:23 - error TS2307: Cannot find module 'stream'.

1531  write(stream: import('stream').Stream, options?: Partial<CsvWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1828:19 - error TS2307: Cannot find module 'stream'.

1828            stream: import('stream').Stream;
                               ~~~~~~~~
node_modules/exceljs/index.d.ts:1872:34 - error TS2503: Cannot find namespace 'NodeJS'.

1872             dictionary: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default                                      ~~~~~~

here is app.component.html

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

        <button class="btn btn-secondary" (click)='downloadExcel()'>Download as Excel</button>

here is app.component.ts

import { Component } from '@angular/core';
import * as Excel from 'exceljs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'resttest10';

  async downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];

    worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

    // save under export.xlsx
    await workbook.xlsx.writeFile('export.xlsx');

    // load a copy of export.xlsx
    const newWorkbook = new Excel.Workbook();
    await newWorkbook.xlsx.readFile('export.xlsx');

    const newworksheet = newWorkbook.getWorksheet('My Sheet');
    newworksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];
    await newworksheet.addRow({ id: 3, name: 'New Guy', dob: new Date(2000, 1, 1) });

    await newWorkbook.xlsx.writeFile('export2.xlsx');

    console.log('File is written');
  }
}

I don't get it why it is looking for stream module (and more funny thing - Cannot find namespace 'NodeJS' - I can run all other angular NodeJS projects without error)

Please point out why i can't export excel.

Body:
You can't write directly a file on client side. that method is mean to be used on backend side in nodejs. if your expectation is download this file on client side. your code should be like :-

import { Component } from "@angular/core";
import * as Excel from "exceljs";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "resttest10";

  async downloadExcel() {
    const date = new Date()
      .toISOString()
      .slice(0, 10)
      .split("-")
      .reverse()
      .join("/");
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet("My Sheet");

    worksheet.columns = [
      { header: "Id", key: "id", width: 10 },
      { header: "Name", key: "name", width: 32 },
      { header: "D.O.B.", key: "dob", width: 15 }
    ];

    worksheet.addRow({ id: 1, name: "John Doe", dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: "Jane Doe", dob: new Date(1965, 1, 7) });

    workbook.xlsx.writeBuffer().then((data: any) => {
      console.log("buffer");
      const blob = new Blob([data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      document.body.appendChild(a);
      a.setAttribute("style", "display: none");
      a.href = url;
      a.download = "export.xlsx";
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    });
  }
}


问:
ConditionalCheckFailedException occurs in the first item in DynamoDB Optimistic locking
I am trying to setup an Optimistic version check before I update the record in DynamoDB.
But I keep getting ConditionalCheckFailedException from the first item save - when there is no hash key existing.

Can someone tell me what's wrong in my code?

Here's my code

```<code>final DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder();
builder.setConsistentReads(DynamoDBMapperConfig.ConsistentReads.CONSISTENT);
builder.setTableNameOverride(new DynamoDBMapperConfig.TableNameOverride(tableName));
DynamoDBMapperConfig mapperConfig = builder.build();
this.dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB, mapperConfig);
</code>```

```<code>@Data
@DynamoDBTable(tableName = "OVERRIDE_AT_RUNTIME")
public class ItemRecord
{
    public static final String CONTENT_ID = "content_id";
    public static final String ACTION_COUNT = "action_count";
    private static final String VERSION = "version";

    @DynamoDBHashKey(attributeName = CONTENT_ID)
    private String contentId;
    @DynamoDBAttribute(attributeName = ACTION_COUNT)
    private int actionCount;
    @DynamoDBVersionAttribute(attributeName = VERSION)
    private long version;

    public TitleMatchProgressRecord() {}

    public TitleMatchProgressRecord(final String contentId)
    {
        this.contentId = contentId;
        this.actionCount = 0;
    }

    @DynamoDBIgnore
    public void incrementActionCount()
    {
        actionCount++;
    }
}
</code>```

```<code>try {
    ItemRecord itemRecord = loadRecord(contentId);
    if (itemRecord == null) { // first item
        itemRecord = new ItemRecord(contentId);
        itemRecord.incrementActionCount();
        DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
        final Map<String, ExpectedAttributeValue> expectedAttributes = new HashMap<>();
        expectedAttributes.put(ItemRecord.CONTENT_ID, new ExpectedAttributeValue(false));
        saveExpression.setExpected(expectedAttributes);

        dynamoDBMapper.save(itemRecord, saveExpression);

    } else {
        itemRecord.incrementActionCount();
        itemRecord.resetLastModifiedAt();
        dynamoDBMapper.save(itemRecord);
    }
} catch (ConditionalCheckFailedException e) {
    // retry
}
</code>```

Error trace:

```<code>   [testng] com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException: The conditional request failed (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ConditionalCheckFailedException; Request ID: UV4V9BSIE78ETRQC9LG4BOB23; Proxy: null)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1811)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1395)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1371)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1145)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:802)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:770)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:744)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:704)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:686)
   [testng]     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:550)
   [testng]     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:530)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:5110)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:5077)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executeUpdateItem(AmazonDynamoDBClient.java:4696)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:4662)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doUpdateItem(DynamoDBMapper.java:871)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$2.executeLowLevelRequest(DynamoDBMapper.java:611)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:750)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:640)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:123)
</code>```

答:
To do "optimistic locking" in DynamoDB, you keep a version attribute on items - which you called "action count". If there is a possibility that the item did not exist yet, and needs to be created for the first time - you must handle this case explicitly. You cannot just assume the item always exists and has a previous action count... For example, you can do this:

Read the item (you can do the read with the cheaper "eventual consistency"). The item may not previously exist - this is fine.

Based on what you read, create the new version of the item. Increment "action count" by one if the item existed, or if it didn't, set action count to 0.

Perform the write, with a condition expression. If the item previously existed, the condition should require that the action count is still equal to its read (pre-increment) value. If the item did not previously exist, the condition should be that the item does not exit.

If the conditional update failed on a failed condition, goto 1 to try again.

Note how if two concurrent writes try to create a new item, one will succeed to create it (with action count 0) and the other will need to try again and actually update the item (resulting eventually with action count 1).

Body:
I am trying to setup an Optimistic version check before I update the record in DynamoDB.
But I keep getting ConditionalCheckFailedException from the first item save - when there is no hash key existing.

Can someone tell me what's wrong in my code?

Here's my code

final DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder();
builder.setConsistentReads(DynamoDBMapperConfig.ConsistentReads.CONSISTENT);
builder.setTableNameOverride(new DynamoDBMapperConfig.TableNameOverride(tableName));
DynamoDBMapperConfig mapperConfig = builder.build();
this.dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB, mapperConfig);

@Data
@DynamoDBTable(tableName = "OVERRIDE_AT_RUNTIME")
public class ItemRecord
{
    public static final String CONTENT_ID = "content_id";
    public static final String ACTION_COUNT = "action_count";
    private static final String VERSION = "version";

    @DynamoDBHashKey(attributeName = CONTENT_ID)
    private String contentId;
    @DynamoDBAttribute(attributeName = ACTION_COUNT)
    private int actionCount;
    @DynamoDBVersionAttribute(attributeName = VERSION)
    private long version;

    public TitleMatchProgressRecord() {}

    public TitleMatchProgressRecord(final String contentId)
    {
        this.contentId = contentId;
        this.actionCount = 0;
    }

    @DynamoDBIgnore
    public void incrementActionCount()
    {
        actionCount++;
    }
}

try {
    ItemRecord itemRecord = loadRecord(contentId);
    if (itemRecord == null) { // first item
        itemRecord = new ItemRecord(contentId);
        itemRecord.incrementActionCount();
        DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
        final Map<String, ExpectedAttributeValue> expectedAttributes = new HashMap<>();
        expectedAttributes.put(ItemRecord.CONTENT_ID, new ExpectedAttributeValue(false));
        saveExpression.setExpected(expectedAttributes);

        dynamoDBMapper.save(itemRecord, saveExpression);

    } else {
        itemRecord.incrementActionCount();
        itemRecord.resetLastModifiedAt();
        dynamoDBMapper.save(itemRecord);
    }
} catch (ConditionalCheckFailedException e) {
    // retry
}

Error trace:

   [testng] com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException: The conditional request failed (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ConditionalCheckFailedException; Request ID: UV4V9BSIE78ETRQC9LG4BOB23; Proxy: null)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1811)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1395)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1371)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1145)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:802)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:770)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:744)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:704)
   [testng]     at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:686)
   [testng]     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:550)
   [testng]     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:530)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:5110)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:5077)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executeUpdateItem(AmazonDynamoDBClient.java:4696)
   [testng]     at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:4662)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doUpdateItem(DynamoDBMapper.java:871)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$2.executeLowLevelRequest(DynamoDBMapper.java:611)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:750)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:640)
   [testng]     at com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:123)