问:
Writing groovy contract for spring cloud contract testing
I am new to contract testing and want to write a groovy contract for a response which contains sub objects with strings list of dictionaries and so on.
I have a response like this:

```<code>{
    "data": [
      {
        "categories": [
          {
            "categories": [],
            "oid": "abc",
            "type": "xyz"
          },
          {
            "categories": [],
            "oid": "abb",
            "type": "xyy"
          }
        ],
        "oid": "ab"
      }
    ],
    "meta": {
      "datatype": "text",
      "language": "x",
      "market": "qw",
      "provider": "AFP",
      "status": "ok",
      "statusInfo": {},
      "supportedLanguages": [
        "x"
      ]
    }
  }
</code>```

and for that I have written the following contract:

```<code>Contract.make {
    request {
        method 'GET'
        url '/foo'
    }
    response {
        status 200
        body(
                 "data"  : [
                     (
                        "categories": [
                            (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyz"
                            ),
                            (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyy"
                            )
                        ]
                        "oid" : regex('\w')
                     )
                 ],
                 "meta" : (
                    "datatype": "text",
                    "language": "x",
                    "market": "qw",
                    "provider": "AFP",
                    "status": "ok",
                    "statusInfo": (),
                    "supportedLanguages": ["x"]
                 )
        )
        headers {
            contentType(applicationJson())
        }
    }
}
</code>```

But is not working properly.
Can you help me to know what I am doing wrong over here.

答:
Your contract is invalid. You're using parentheses where you should be using brackets</p>
```<code>Contract.make {
    request {
        method 'GET'
        url '/foo'
    }
    response {
        status 200
        body(
                 "data"  : [
                     (
                        "categories": [
                            [ // was (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyz"
                            ], // was )
                            [ // was (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyy"
                            ] // was )
                        ]
                        "oid" : regex('\w')
                     )
                 ],
                 "meta" : [ // was (
                    "datatype": "text",
                    "language": "x",
                    "market": "qw",
                    "provider": "AFP",
                    "status": "ok",
                    "statusInfo": [:], // was ()
                    "supportedLanguages": ["x"]
                 ] // was )
        )
        headers {
            contentType(applicationJson())
        }
    }
}
</code>```

Body:
I am new to contract testing and want to write a groovy contract for a response which contains sub objects with strings list of dictionaries and so on.
I have a response like this:

{
    "data": [
      {
        "categories": [
          {
            "categories": [],
            "oid": "abc",
            "type": "xyz"
          },
          {
            "categories": [],
            "oid": "abb",
            "type": "xyy"
          }
        ],
        "oid": "ab"
      }
    ],
    "meta": {
      "datatype": "text",
      "language": "x",
      "market": "qw",
      "provider": "AFP",
      "status": "ok",
      "statusInfo": {},
      "supportedLanguages": [
        "x"
      ]
    }
  }

and for that I have written the following contract:

Contract.make {
    request {
        method 'GET'
        url '/foo'
    }
    response {
        status 200
        body(
                 "data"  : [
                     (
                        "categories": [
                            (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyz"
                            ),
                            (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyy"
                            )
                        ]
                        "oid" : regex('\w')
                     )
                 ],
                 "meta" : (
                    "datatype": "text",
                    "language": "x",
                    "market": "qw",
                    "provider": "AFP",
                    "status": "ok",
                    "statusInfo": (),
                    "supportedLanguages": ["x"]
                 )
        )
        headers {
            contentType(applicationJson())
        }
    }
}

But is not working properly.
Can you help me to know what I am doing wrong over here.

Body:
Your contract is invalid. You're using parentheses where you should be using brackets

Contract.make {
    request {
        method 'GET'
        url '/foo'
    }
    response {
        status 200
        body(
                 "data"  : [
                     (
                        "categories": [
                            [ // was (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyz"
                            ], // was )
                            [ // was (
                            "categories" : [],
                            "oid" : anyNonEmptyString(),
                            "type" : "xyy"
                            ] // was )
                        ]
                        "oid" : regex('\w')
                     )
                 ],
                 "meta" : [ // was (
                    "datatype": "text",
                    "language": "x",
                    "market": "qw",
                    "provider": "AFP",
                    "status": "ok",
                    "statusInfo": [:], // was ()
                    "supportedLanguages": ["x"]
                 ] // was )
        )
        headers {
            contentType(applicationJson())
        }
    }
}


来源: stackexchange

问:
How can I close my dropdown menu when sveltekit route changes?
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

```<code><script>
    import { page } from '$app/stores';
    import { onDestroy } from 'svelte';
    let isMainNavOpen = true;
    let isGroupNavOpen = false;
    function toggleGroupMenu(e) {
        e.preventDefault();

        isGroupNavOpen = !isGroupNavOpen;
    }

    $: currentPath = $page.url.pathname;
</script>

    <nav>
        <header class="groups" class:closed={!isGroupNavOpen}>
            <div class="dropdown">
                <a href="#" class="toggler" on:click|preventDefault={toggleGroupMenu}>
                    <img src="/icons/chevron.svg" alt="" border="0" />
                </a>
                <ul>
                    {#each groupMenu as item, i}
                        <li class:active={currentPath === item.path}>
                            <a href="/groups/{item.id}"
                                ><img
                                    class="avatar"
                                    src="/icons/avatar.group.png"
                                    alt=""
                                    border="0"
                                />{item.name}</a
                            >
                        </li>
                    {/each}
                </ul>
                <a href="/groups" class="button secondary outlined">Explore Groups</a>
            </div>
        </header>
    </nav>

<style>
    nav {
        padding: 1.2rem;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
    }

    nav header {
        color: #fff;
        display: flex;
        flex-direction: column;
    }

    .groups.closed li:not(:first-child) {
        display: none;
    }

    .groups .toggler {
        position: absolute;
        top: 2.5rem;
        right: 1rem;
        margin-left: 1.4rem;
    }

    .groups .toggler img {
        transform: rotate(180deg);
    }

    .groups.closed .toggler img {
        transform: rotate(0deg);
    }

    .groups ul {
        width: 100%;
        max-height: 22rem;
        overflow-y: auto;
        background-color: #060536;
        color: #fff;
        border-radius: 0.8rem;
    }

    .groups ul .active {
        background-color: #34326d;
    }

    .groups .dropdown {
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        background-color: #060536;
    }

    header.groups {
        padding: 0;
        position: relative;
        overflow: visible;
    }

    .groups .avatar {
        width: 5rem;
        display: block;
        margin-right: 1.4rem;
    }

    .groups li {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .groups li a {
        padding: 1rem;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-grow: 1;
        color: #fff;
        text-decoration: none;
        font-weight: 600;
        word-break: break-all;
    }

    .groups .button {
        font-weight: 600;
        font-size: 1.4rem;
        width: 80%;
        margin: 1rem auto;
    }

    .groups.closed .button {
        display: none;
    }

    nav ul {
        display: flex;
        flex-direction: column;
    }

    nav ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        flex: 1;
    }
</style>
</code>```

I probably also need an underlay where if they click off the menu it closes too.

答:
I used a setTimeout to toggle the style display property of the menu content, which closes the menu content after the click:

```<code><script>
  ...
  let display = "";  // Svelte style property
  ...
</script>

<div class="nav-menu">
  <div class:active class="menu-btn">
    <span>{text}</span>
    <i class="fa fa-caret-down" />
  </div>
  <div
    class="menu-content"
    style:display
    on:click={() => {
      display = "none";
      setTimeout(() => (display = ""), 0);
    }}>
    <slot />
  </div>
</div>
</code>```

Update:

Removed stopPropagation in the on:click.

The Sveltekit filesystem-based router needs this click!

ContentLicense: CC BY-SA 4.0

Body:
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

                    {#each groupMenu as item, i}

                            {item.name}

                    {/each}

                Explore Groups

I probably also need an underlay where if they click off the menu it closes too.

Body:
I used a setTimeout to toggle the style display property of the menu content, which closes the menu content after the click:

<script>
  ...
  let display = "";  // Svelte style property
  ...
</script>

<div class="nav-menu">
  <div class:active class="menu-btn">
    <span>{text}</span>
    <i class="fa fa-caret-down" />
  </div>
  <div
    class="menu-content"
    style:display
    on:click={() => {
      display = "none";
      setTimeout(() => (display = ""), 0);
    }}>
    <slot />
  </div>
</div>

Update:

Removed stopPropagation in the on:click.

The Sveltekit filesystem-based router needs this click!


问:
What is the best way to randomly sample key, value pairs from a dictionary?
Suppose one has a dictionary and wants to randomly sample a subset of key/value pairs, what is the best way to do this?

Previously, I would use random.sample but apparently this functionality will be deprecated for sets.  Is there existing functionality that can produce the same result?

```<code>In [1]: dct = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}

In [2]:{k:v for k,v in random.sample(dct.items(),1)}
<ipython-input-33-f99661a57cc1>:1: DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.
  {k:v for k,v in random.sample(dct.items(),1)}
Out[2]: {'a': [1, 2, 3]}
</code>```

答:
You can just convert the set into a list.

import random

dct = {'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]}

# Sample 2 keys from the dict
random.sample(list(dct.items()), 2))
```

Body:
Suppose one has a dictionary and wants to randomly sample a subset of key/value pairs, what is the best way to do this?

Previously, I would use random.sample but apparently this functionality will be deprecated for sets.  Is there existing functionality that can produce the same result?

In [1]: dct = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}

In [2]:{k:v for k,v in random.sample(dct.items(),1)}
<ipython-input-33-f99661a57cc1>:1: DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.
  {k:v for k,v in random.sample(dct.items(),1)}
Out[2]: {'a': [1, 2, 3]}


问:
Accessing a Custom Configuration Section in .Net
I am trying to access settings in my config file, which is a series of xml elements listed as such:

```<code><databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>
</code>```

Now I want to access it. I have set up classes like so:

```<code>Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class
</code>```

I want to be able get the element by it's name and return the value but I can't see to do that:

```<code>Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")
</code>```

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

答:
There isn't any good reason to design this kind of stuff by hand anymore.  Rather, you should be using the Configuration Section Designer on CodePlex:

http://csd.codeplex.com/

Once installed, you can just add a new item to your project (a configuration section designer) and then add the elements and the constraints.  I've found it VERY easy to use, and I will probably never write a piece of code for configuration files again.

OwnerDisplayName: Damien

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access settings in my config file, which is a series of xml elements listed as such:

<databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>

Now I want to access it. I have set up classes like so:

Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class

I want to be able get the element by it's name and return the value but I can't see to do that:

Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

OwnerDisplayName: casperOne


问:
How to get current route name in react-navigation?
I want the name of the current route or screen in react-navigation which I want to use inside if condition to make some changes.</p>

答:
Try this,

```<code>const appNavigation = useNavigation();
const currentRoute = appNavigation.getCurrentRoute();
</code>```

This worked for me. Navigation, and its state received as props were unreliable(at least for drawer navigator at root).
So I went with this one, which seems to be giving the global navigation state.

Had to use the navigation prop being received in drawer for drawer specific functions like closeDrawer or openDrawer.

```<code>export function AppDrawer(props) {

   // for closeDrawer, openDrawer etc.
   const { navigation: drawerNavigation } = props;

   // for referencing current route
   const appNavigation = useNavigation();
   const currentRoute = appNavigation.getCurrentRoute();

   // ... rest of the code
}
</code>```

Reference for both the variable in console -

Body:
Try this,

const appNavigation = useNavigation();
const currentRoute = appNavigation.getCurrentRoute();

This worked for me. Navigation, and its state received as props were unreliable(at least for drawer navigator at root).
So I went with this one, which seems to be giving the global navigation state.

Had to use the navigation prop being received in drawer for drawer specific functions like closeDrawer or openDrawer.

export function AppDrawer(props) {

   // for closeDrawer, openDrawer etc.
   const { navigation: drawerNavigation } = props;

   // for referencing current route
   const appNavigation = useNavigation();
   const currentRoute = appNavigation.getCurrentRoute();

   // ... rest of the code
}

Reference for both the variable in console -


问:
kubernetes persistent volume accessmode
It seems that Kubernetes supports 3 kinds of access mode for persistent volume: ReadWriteOnce, ReadOnlyMany, ReadWriteMany.
I'm really curious about the scheduler strategy for a pod which uses the ReadWriteOnce mode volume. For example, I created an RC which have pod num=2, I guess the two pods will be scheduled into the same host because they use the volume that has ReadWriteOnce mode?
I really want to know the source code of this part.

答:
In Kubernetes you provision storage either statically(using a storage class) or dynamically (Persistent Volume). Once the storage is available to bound and claimed, you need to configure it in what way your Pods or Nodes are connecting to the storage (a persistent volume). That could be configured in below four modes.

ReadOnlyMany (ROX)

In this mode multiple pods running on different Nodes could connect to the storage and carry out read operation.

ReadWriteMany (RWX)

In this mode multiple pods running on different Nodes could connect to the storage and carry out read and write operation.

ReadWriteOnce (RWO)

In this mode multiple pods running in only one Node could connect to the storage and carry out read and write operation.

ReadWriteOncePod (RWOP)

In this mode the volume can be mounted as read-write by a single Pod. Use ReadWriteOncePod access mode if you want to ensure that only one pod across whole cluster can read that PVC or write to it. This is only supported for CSI volumes and Kubernetes version 1.22+.

Follow the documentation to get more insight.

Title: kubernetes persistent volume accessmode


问:
Filepath opening multiple times in VBA
I want to bring data from another excel file, the code below works as intended, XLookup does the job BUT Windows file picker opens three times with this code. Can anyone advise why?
I've got one variable and two references to it in the formula.

Dim FileToOpen As Variant
FileToOpen = Application.GetOpenFilename()
Range("B1").Select
ActiveCell.Formula2R1C1 = _
        "=XLOOKUP(RC[-1]:R[79]C[-1],'& FileToOpen &'!R11C1:R57C1,'& FileToOpen &'!R11C2:R57C2,""Not Found"",0)"
```

答:
You need to distinguish between Excel and VBA. In VBA, you have a variable named FileToOpen that contains a filename. In Excel, this variable is unknown.

What you want to do is to write the content of the variable into a string. That string will then be written as a formula into a cell. Therefore you need to do some string concatenation in VBA. With you current code, VBA sees only one single string. It cannot look into that string, see that a part of a string is a variable name and replace the name with the content. Everything between the double quotes in left untouched by VBA - except if you have a pair of double quotes, this tells VBA that you want a (single) double quote character within the string.

If you want to write a formula with VBA, my advice is always to write the formula into a intermediate string variable that you can easily check with the debugger.

Change your code to

```<code>Dim formula As String
formula = "=XLOOKUP(RC[-1]:R[79]C[-1],'" & FileToOpen & "'!R11C1:R57C1,'" & FileToOpen & "'!R11C2:R57C2,""Not Found"",0)"
Debug.Print formula
ActiveCell.Formula2R1C1 = formula
</code>```

See the difference? Now your formula is build from (5) pieces that VBA sees, and it will conatenate the pieces of the formula and the content of your variable.

Title: Filepath opening multiple times in VBA

Body:
You need to distinguish between Excel and VBA. In VBA, you have a variable named FileToOpen that contains a filename. In Excel, this variable is unknown.

What you want to do is to write the content of the variable into a string. That string will then be written as a formula into a cell. Therefore you need to do some string concatenation in VBA. With you current code, VBA sees only one single string. It cannot look into that string, see that a part of a string is a variable name and replace the name with the content. Everything between the double quotes in left untouched by VBA - except if you have a pair of double quotes, this tells VBA that you want a (single) double quote character within the string.

If you want to write a formula with VBA, my advice is always to write the formula into a intermediate string variable that you can easily check with the debugger.

Change your code to

Dim formula As String
formula = "=XLOOKUP(RC[-1]:R[79]C[-1],'" & FileToOpen & "'!R11C1:R57C1,'" & FileToOpen & "'!R11C2:R57C2,""Not Found"",0)"
Debug.Print formula
ActiveCell.Formula2R1C1 = formula

See the difference? Now your formula is build from (5) pieces that VBA sees, and it will conatenate the pieces of the formula and the content of your variable.


问:
How to use Google Properties Service to store data and refer them for various purpose?
I need help with Google Properties Service. Actually, I have created a sidebar in google sheet to store the data into the sheet and used that data to send an email and set up a trigger, but now I want to store that multiple data directly into the Properties Service and refer them to send an email (with stored data) and set up the trigger.

For reference, I am attaching my code. If there is any easy way to code then kindly suggest it.

Any help is highly appreciated.

Code.js

```<code>function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sidebar')
    .addItem('Show sidebar', 'showSidebar')
    .addToUi();
}

var SHEET = SpreadsheetApp.getActiveSheet();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = SHEET.getRange('B1').getValue();
var emailAddress = SHEET.getRange('B2').getValue();
var mobileNumber = SHEET.getRange('B3').getValue();
var city = SHEET.getRange('B4').getValue();
var weekDay = SHEET.getRange('B5').getValue();
var triggerTime = SHEET.getRange('B6').getValue();

function showSidebar() {
  var ui = SpreadsheetApp.getUi();
  var tmp = HtmlService.createTemplateFromFile('index');
  tmp.fullNameValue = fullNameValue();
  tmp.emailAddressValue = emailAddressValue();
  tmp.mobileNumberValue = mobileNumberValue();
  tmp.cityValue = cityValue();
  tmp.dayValue = dayValue();
  tmp.timeValue = timeValue();

  var html = tmp.evaluate();
  html.setTitle('Sidebar');
  ui.showSidebar(html);
}

function include(File) {
  return HtmlService.createHtmlOutputFromFile(File).getContent();
};

function fullNameValue() { return SHEET.getRange(1, 2).getValue(); }
function setfullName(inputfullName) { return SHEET.getRange(1, 2).setValue(inputfullName); }

function emailAddressValue() { return SHEET.getRange(2, 2).getValue(); }
function setEmailAddress(inputEmailAddress) { return SHEET.getRange(2, 2).setValue(inputEmailAddress); }

function mobileNumberValue() { return SHEET.getRange(3, 2).getValue(); }
function setmobileNumber(imputmobileNumber) { return SHEET.getRange(3, 2).setValue(imputmobileNumber); }

function cityValue() { return SHEET.getRange(4, 2).getValue(); }
function setCity(inputCity) { return SHEET.getRange(4, 2).setValue(inputCity); }

function dayValue() { return SHEET.getRange(5, 2).getValue(); }
function setDay(inputDay) { return SHEET.getRange(5, 2).setValue(inputDay); }

function timeValue() { return SHEET.getRange(6, 2).getValue(); }
function setTime(inputTime) { return SHEET.getRange(6, 2).setValue(inputTime); }

function sendEmail() {
  var subject = 'Your request has been received.';
  var body = 'Dear ' + fullName + ', We have received your request. Your details are, name: ' + fullName + ', email address: ' + emailAddress + ', mobile number: ' + mobileNumber + ', city: ' + city;

  GmailApp.sendEmail(emailAddress, subject, body, {
    from: emailFrom,
    htmlBody: body
  });
};

function setTrigger() {
  ScriptApp.newTrigger('sendEmail').timeBased().everyDays(1).atHour(triggerTime).create();
  ScriptApp.newTrigger('sendEmail').timeBased().onWeekDay(ScriptApp.WeekDay.MONDAY).atHour(triggerTime).create();
};
</code>```

index.html

```<code><!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <style>
    .form-row {
      margin-bottom: 15px;
    }
  </style>

</head>

<body>

  <div class="container">

    <div class="row">
      <div class="input-field col s12">
        <input id="fullName" type="text" class="validate">
        <label class="active" for="fullName">Full Name</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="emailAddress" type="text" class="validate">
        <label for="emailAddress">Email Address</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="mobileNumber" type="number" class="validate">
        <label for="mobileNumber">Mobile Number</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="city" type="text" class="validate">
        <label for="city">City</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <select id="day">
<option value="">Choose</option>
<option value="MONDAY">MONDAY</option>
<option value="TUESDAY">TUESDAY</option>
<option value="WEDNESDAY">WEDNESDAY</option>
<option value="THURSDAY">THURSDAY</option>
<option value="FRIDAY">FRIDAY</option>
<option value="SATURDAY">SATURDAY</option>
<option value="SUNDAY">SUNDAY</option>
</select>
        <label>Select Day</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <select id="time">
<option value="">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
        <label>Select Time</label>
      </div>
    </div>

    <div class="row">
      <button id="btn" class="btn waves-effect waves-light" type="submit" name="action">Submit</button>
    </div>

    <div class="row">
      <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>
    </div>

  </div>

  <script>
    var fullNameBox = <?= fullNameValue ?>;
document.getElementById('fullName').value = fullNameBox;
document.getElementById('btn').addEventListener('click',function(){
var inputfullName = document.getElementById('fullName').value;
google.script.run.setfullName(inputfullName);
});
  </script>

  <script>
    var emailAddressBox = <?= emailAddressValue ?>;
document.getElementById('emailAddress').value = emailAddressBox;
document.getElementById('btn').addEventListener('click',function(){
var inputEmailAddress = document.getElementById('emailAddress').value;
google.script.run.setEmailAddress(inputEmailAddress);
});
  </script>

  <script>
    var mobileNumberBox = <?= mobileNumberValue ?>;
document.getElementById('mobileNumber').value = mobileNumberBox;
document.getElementById('btn').addEventListener('click',function(){
var imputmobileNumber = document.getElementById('mobileNumber').value;
google.script.run.setmobileNumber(imputmobileNumber);
});
  </script>

  <script>
    var cityBox = <?= cityValue ?>;
document.getElementById('city').value = cityBox;
document.getElementById('btn').addEventListener('click',function(){
var inputCity = document.getElementById('city').value;
google.script.run.setCity(inputCity);
});
  </script>

  <script>
    var selectDay = <?= dayValue ?>;
document.getElementById('day').value = selectDay;
document.getElementById('btn').addEventListener('click',function(){
var inputDay = document.getElementById('day').value;
google.script.run.setDay(inputDay);
});
  </script>

  <script>
    var selectTime = <?= timeValue ?>;
document.getElementById('time').value = selectTime;
document.getElementById('btn').addEventListener('click',function(){
var inputTime = document.getElementById('time').value;
google.script.run.setTime(inputTime);
});
  </script>

  <script>
    document.getElementById('btn').addEventListener('click',function(){
var setTrigger = document.getElementById('btn').value;
google.script.run.setupTrigger(setTrigger);
});

  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
    });
  </script>

</body>

</html>
</code>```

答:
There are 3 types of PropertiesService, for the general purpose, probably scriptPorperties will be the most suitable ones

To store values in the script properties, you need to use the method setProperty(key, value) or setProperties(properties)

To retrieve values, use getProperty(key) or getProperties()

Sample for getting properties

From

var SHEET = SpreadsheetApp.getActiveSheet();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = SHEET.getRange('B1').getValue();
var emailAddress = SHEET.getRange('B2').getValue();
var mobileNumber = SHEET.getRange('B3').getValue();
var city = SHEET.getRange('B4').getValue();
var weekDay = SHEET.getRange('B5').getValue();
var triggerTime = SHEET.getRange('B6').getValue();

```
<p>modify to</p>
<pre class="lang-js prettyprint-override"><code>var scriptProperties = PropertiesService.getScriptProperties();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = scriptProperties.getProperty('fullName');
var emailAddress = scriptProperties.getProperty('emailAddress');
var mobileNumber = scriptProperties.getProperty('mobileNumber');
var city = scriptProperties.getProperty('city');
var weekDay = scriptProperties.getProperty('weekDay');
var triggerTime = scriptProperties.getProperty('triggerTime');

</code>```

and from

function fullNameValue() { return SHEET.getRange(1, 2).getValue(); }
```
<p>to</p>
<pre class="lang-js prettyprint-override"><code>// make sure scriptProperties is a global variable
function fullNameValue() {
  return scriptProperties.getProperty('fullName');
}
</code>```

Same for your other functions.

Sample for setting properties

From

function setfullName(inputfullName) { return SHEET.getRange(1, 2).setValue(inputfullName); }
```
<p>modify to</p>
<pre class="lang-js prettyprint-override"><code>//skip the first line if scriptProperties is already defined as a global vairiable
function setfullName(inputfullName) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty("inputfullName", inputfullName);
}
</code>```

NOTE:

Curently, a big part of your code (the one to get values) is located outside of a function and runs globally

If you try to access a script property that does not exist - it will be undefined. Make sure to out the code block accessing values into (a) function(s) that will only be called after you have set the properties frist.

PropertiesService converts all dat to strings. If you need to process data as numbers (e.g. mobileNumber), it's best practive to use JSON.stringify() and JSON.parse() when wroking with script properties.

Sample:

function setmobileNumber(mobileNumber) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty("mobileNumber",
  JSON.stringify(mobileNumber));
}
function mobileNumberValue() {
  var mobileNumber = scriptProperties.getProperty('mobileNumber');
  //check if defined
  if(mobileNumber){
    mobileNumber = JSON.parse(mobileNumber);
    return scriptProperties.getProperty('mobileNumber');
   }
}
```

Body:
I need help with Google Properties Service. Actually, I have created a sidebar in google sheet to store the data into the sheet and used that data to send an email and set up a trigger, but now I want to store that multiple data directly into the Properties Service and refer them to send an email (with stored data) and set up the trigger.

For reference, I am attaching my code. If there is any easy way to code then kindly suggest it.

Any help is highly appreciated.

Code.js

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sidebar')
    .addItem('Show sidebar', 'showSidebar')
    .addToUi();
}

var SHEET = SpreadsheetApp.getActiveSheet();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = SHEET.getRange('B1').getValue();
var emailAddress = SHEET.getRange('B2').getValue();
var mobileNumber = SHEET.getRange('B3').getValue();
var city = SHEET.getRange('B4').getValue();
var weekDay = SHEET.getRange('B5').getValue();
var triggerTime = SHEET.getRange('B6').getValue();

function showSidebar() {
  var ui = SpreadsheetApp.getUi();
  var tmp = HtmlService.createTemplateFromFile('index');
  tmp.fullNameValue = fullNameValue();
  tmp.emailAddressValue = emailAddressValue();
  tmp.mobileNumberValue = mobileNumberValue();
  tmp.cityValue = cityValue();
  tmp.dayValue = dayValue();
  tmp.timeValue = timeValue();

  var html = tmp.evaluate();
  html.setTitle('Sidebar');
  ui.showSidebar(html);
}

function include(File) {
  return HtmlService.createHtmlOutputFromFile(File).getContent();
};

function fullNameValue() { return SHEET.getRange(1, 2).getValue(); }
function setfullName(inputfullName) { return SHEET.getRange(1, 2).setValue(inputfullName); }

function emailAddressValue() { return SHEET.getRange(2, 2).getValue(); }
function setEmailAddress(inputEmailAddress) { return SHEET.getRange(2, 2).setValue(inputEmailAddress); }

function mobileNumberValue() { return SHEET.getRange(3, 2).getValue(); }
function setmobileNumber(imputmobileNumber) { return SHEET.getRange(3, 2).setValue(imputmobileNumber); }

function cityValue() { return SHEET.getRange(4, 2).getValue(); }
function setCity(inputCity) { return SHEET.getRange(4, 2).setValue(inputCity); }

function dayValue() { return SHEET.getRange(5, 2).getValue(); }
function setDay(inputDay) { return SHEET.getRange(5, 2).setValue(inputDay); }

function timeValue() { return SHEET.getRange(6, 2).getValue(); }
function setTime(inputTime) { return SHEET.getRange(6, 2).setValue(inputTime); }

function sendEmail() {
  var subject = 'Your request has been received.';
  var body = 'Dear ' + fullName + ', We have received your request. Your details are, name: ' + fullName + ', email address: ' + emailAddress + ', mobile number: ' + mobileNumber + ', city: ' + city;

  GmailApp.sendEmail(emailAddress, subject, body, {
    from: emailFrom,
    htmlBody: body
  });
};

function setTrigger() {
  ScriptApp.newTrigger('sendEmail').timeBased().everyDays(1).atHour(triggerTime).create();
  ScriptApp.newTrigger('sendEmail').timeBased().onWeekDay(ScriptApp.WeekDay.MONDAY).atHour(triggerTime).create();
};

index.html

<!DOCTYPE html>

  <base target="_top">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

        <input id="fullName" type="text" class="validate">
        Full Name

        <input id="emailAddress" type="text" class="validate">
        Email Address

        <input id="mobileNumber" type="number" class="validate">
        Mobile Number

        <input id="city" type="text" class="validate">
        City

        <select id="day">
<option value="">Choose</option>
<option value="MONDAY">MONDAY</option>
<option value="TUESDAY">TUESDAY</option>
<option value="WEDNESDAY">WEDNESDAY</option>
<option value="THURSDAY">THURSDAY</option>
<option value="FRIDAY">FRIDAY</option>
<option value="SATURDAY">SATURDAY</option>
<option value="SUNDAY">SUNDAY</option>
</select>
        Select Day

        <select id="time">
<option value="">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
        Select Time

      <button id="btn" class="btn waves-effect waves-light" type="submit" name="action">Submit</button>

      <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>

Body:
There are 3 types of PropertiesService, for the general purpose, probably scriptPorperties will be the most suitable ones

To store values in the script properties, you need to use the method setProperty(key, value) or setProperties(properties)

To retrieve values, use getProperty(key) or getProperties()

Sample for getting properties

From

var SHEET = SpreadsheetApp.getActiveSheet();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = SHEET.getRange('B1').getValue();
var emailAddress = SHEET.getRange('B2').getValue();
var mobileNumber = SHEET.getRange('B3').getValue();
var city = SHEET.getRange('B4').getValue();
var weekDay = SHEET.getRange('B5').getValue();
var triggerTime = SHEET.getRange('B6').getValue();

modify to

var scriptProperties = PropertiesService.getScriptProperties();
var emailFrom = Session.getActiveUser().getEmail();
var fullName = scriptProperties.getProperty('fullName');
var emailAddress = scriptProperties.getProperty('emailAddress');
var mobileNumber = scriptProperties.getProperty('mobileNumber');
var city = scriptProperties.getProperty('city');
var weekDay = scriptProperties.getProperty('weekDay');
var triggerTime = scriptProperties.getProperty('triggerTime');

and from

function fullNameValue() { return SHEET.getRange(1, 2).getValue(); }

to

// make sure scriptProperties is a global variable
function fullNameValue() {
  return scriptProperties.getProperty('fullName');
}

Same for your other functions.

Sample for setting properties

From

function setfullName(inputfullName) { return SHEET.getRange(1, 2).setValue(inputfullName); }

modify to

//skip the first line if scriptProperties is already defined as a global vairiable
function setfullName(inputfullName) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty("inputfullName", inputfullName);
}

NOTE:

Curently, a big part of your code (the one to get values) is located outside of a function and runs globally

If you try to access a script property that does not exist - it will be undefined. Make sure to out the code block accessing values into (a) function(s) that will only be called after you have set the properties frist.

PropertiesService converts all dat to strings. If you need to process data as numbers (e.g. mobileNumber), it's best practive to use JSON.stringify() and JSON.parse() when wroking with script properties.

Sample:

function setmobileNumber(mobileNumber) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty("mobileNumber",
  JSON.stringify(mobileNumber));
}
function mobileNumberValue() {
  var mobileNumber = scriptProperties.getProperty('mobileNumber');
  //check if defined
  if(mobileNumber){
    mobileNumber = JSON.parse(mobileNumber);
    return scriptProperties.getProperty('mobileNumber');
   }
}


问:
Show images from folder by scrolling in scrollbar is laggy?
I have 1 picturebox and 1 "VScrollbar" ( vertical scrollbar ).
When i change the value of the scrollbar i want to get a picture from my folder in disk and show the image in the picturebox. I only want to show 1 picture a time.

It works but it is "laggy" because everytime i scroll, i get the index of the scroll, get the file from my folder ( depending on the index of the scroll ) and then making a bitmap and binding it to the picturebox.

```<code>private void ScreenBarScroller_ValueChanged(object sender, EventArgs e)
{
    int scrollValue =
        ScreenBarScroller.Value == 0 ? 0 : ScreenBarScroller.Value - 1;

    ScreenClass currentScreen = ScreenList[scrollValue];

    using (Bitmap newPicture = new Bitmap(
                               new FileStream(currentScreen.Path,
                               FileMode.Open, FileAccess.ReadWrite,
                           FileShare.Delete | FileShare.ReadWrite)))
    {
            pictureBox1.Image =
               ResizeBitmap(newPicture, pictureBox1.Width, pictureBox1.Height);
    }
}
</code>```

The code works but its so damn laggy , i want the "smooth" scrolling . How can i do that? Is there a better way to do this then VScrollbar?

答:
One of possible solutions can be load also images in the range of, let's say, next 5 images in background thread. So at the moment user goes to the next image it's already loaded or at least in loading.

Another solution can be use memory mapping on your bitmaps which will invrease performanse of reading from disk.

Can also merge these 2 solutions.

EDIT

Important is, by me, if these are big enough images, to load them in another thread and notify to the user via message on UI that image is in loading, so you will give sence of responsivness to your app. There is nothing worse for UX to leave user without a clue what is going on now.

ContentLicense: CC BY-SA 3.0

Body:
I have 1 picturebox and 1 "VScrollbar" ( vertical scrollbar ).
When i change the value of the scrollbar i want to get a picture from my folder in disk and show the image in the picturebox. I only want to show 1 picture a time.

It works but it is "laggy" because everytime i scroll, i get the index of the scroll, get the file from my folder ( depending on the index of the scroll ) and then making a bitmap and binding it to the picturebox.

private void ScreenBarScroller_ValueChanged(object sender, EventArgs e)
{
    int scrollValue =
        ScreenBarScroller.Value == 0 ? 0 : ScreenBarScroller.Value - 1;

    ScreenClass currentScreen = ScreenList[scrollValue];

    using (Bitmap newPicture = new Bitmap(
                               new FileStream(currentScreen.Path,
                               FileMode.Open, FileAccess.ReadWrite,
                           FileShare.Delete | FileShare.ReadWrite)))
    {
            pictureBox1.Image =
               ResizeBitmap(newPicture, pictureBox1.Width, pictureBox1.Height);
    }
}

The code works but its so damn laggy , i want the "smooth" scrolling . How can i do that? Is there a better way to do this then VScrollbar?


问:
Service bus queue connector in Logic app is not setting message to complete in first recurrence interval which is causing duplicates
Here are the details of logic app

When a message is received in a queue (auto-complete) Servicebusconnector with recurrence interval of 30 minutes with concurrency control of 20 receives message from service bus
queue.

Lock duration is set to 5 minutes.

Sends the message to SFTP location using sftpConnector

Problem: The last message in first recurrence interval is not being set as complete and the same message is showing up in second recurrence with Deliverycount 2

Not sure what is causing this as there is lot of time difference in runs.

答:
We were able to fix this issue by reducing the recurrence interval to less than service bus queue's lock duration based on Microsoft's documentation.

The auto-complete trigger automatically completes a message, but completion happens only at the next call to Service Bus. This behavior can affect your logic app's design. For example, avoid changing the concurrency on the auto-complete trigger because this change might result in duplicate messages if your logic app workflow enters a throttled state. Changing the concurrency control creates these conditions: throttled triggers are skipped with the WorkflowRunInProgress code, the completion operation won't happen, and next trigger run occurs after the polling interval. You have to set the service bus lock duration to a value that's longer than the polling interval. However, despite this setting, the message still might not complete if your logic app workflow remains in a throttled state at next polling interval.

https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-servicebus
Exchange messages with Azure Service Bus - Azure Logic Apps
Create automated tasks and workflows that send and receive messages by using Azure Service Bus in Azure Logic Apps


问:
How to change the variable value without changing its * value?
I am a newbie in the C language and learning it. I am learning the pointers. I am confused a little about the following program.

My question is it even possible to get the outcome B ever? I am changing the value of a but accordingly, the value of b gets changed due to the pointer and I am always just getting outcome A. How can I get outcome B? Any help will be really appreciated. Thanks :)

```<code>#include <stdio.h>
 void increment(int value) {
    value++;
}
int main() {
   int a = 6;
   int *b = &a;
   increment(a);
   if(a == *b) {
     printf("outcome A");
   } else if(a > *b) {
     printf("outcome B");
   } else {
     printf("outcome C");
   } return 0;
}
</code>```

答:
A pointer is an object in many programming languages that stores a memory address. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer

Take a look at this code snippet

```<code>#include <stdio.h>

int main() {
   int a = 6;
   int *b = &a;

   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b);

   a = 20;

   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b);
}
</code>```

Output:

```<code>a = 6  b = 0x7fff3ead8d6c  *b = 6
a = 20  b = 0x7fff3ead8d6c  *b = 20
</code>```

As you can see, assigning a new value to a did not change the value of b. It did change the value pointed to by b, however. That is, b did not change, while *b did.

Body:
I am a newbie in the C language and learning it. I am learning the pointers. I am confused a little about the following program.

My question is it even possible to get the outcome B ever? I am changing the value of a but accordingly, the value of b gets changed due to the pointer and I am always just getting outcome A. How can I get outcome B? Any help will be really appreciated. Thanks :)

#include <stdio.h>
 void increment(int value) {
    value++;
}
int main() {
   int a = 6;
   int *b = &a;
   increment(a);
   if(a == *b) {
     printf("outcome A");
   } else if(a > *b) {
     printf("outcome B");
   } else {
     printf("outcome C");
   } return 0;
}

Body:
A pointer is an object in many programming languages that stores a memory address. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer

Take a look at this code snippet

#include <stdio.h>

int main() {
   int a = 6;
   int *b = &a;

   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b);

   a = 20;

   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b);
}

Output:

a = 6  b = 0x7fff3ead8d6c  *b = 6
a = 20  b = 0x7fff3ead8d6c  *b = 20

As you can see, assigning a new value to a did not change the value of b. It did change the value pointed to by b, however. That is, b did not change, while *b did.


问:
How to restrict props.children in react typescript?
```<code>import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (
        <div className="App">
            <Message>
                <p>Hello World</p>
            </Message>
            <Message>
                <a>Hello World</a>
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>
        </div>
    );
}

export default App;

</code>```
```<code>import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (
        <h1>
            {children}
        </h1>
    );
};

export default Message;

</code>```

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

答:
I think this is the wrong way to be going about implementing HTMl here: if you want a
 element to render then you shouldn't be passing
 or <button> elements into it.

Why not just leave the functional component input here as just a string? Like so:

```<code>import React from 'react';

interface MessageProps {
    messageText: string;
}

const Message: React.FC<MessageProps> = ({ messageText }) => {

    return (
        <h1>
            {messageText}
        </h1>
    );
};

export default Message;

//////

import React from 'react';
import Message from "./components/Message";

function App() {
    return (
        <div className="App">
            <Message messageText="Hello world" />
        </div>
    );
}

export default App;

</code>```

Body:
import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (

            <Message>

Hello World

            </Message>
            <Message>
                Hello World
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>

    );
}

export default App;

import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (

            {children}

    );
};

export default Message;

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

Body:
I think this is the wrong way to be going about implementing HTMl here: if you want a <h1> element to render then you shouldn't be passing <p> or <button> elements into it.

Why not just leave the functional component input here as just a string? Like so:

import React from 'react';

interface MessageProps {
    messageText: string;
}

const Message: React.FC<MessageProps> = ({ messageText }) => {

    return (
        <h1>
            {messageText}
        </h1>
    );
};

export default Message;

//////

import React from 'react';
import Message from "./components/Message";

function App() {
    return (
        <div className="App">
            <Message messageText="Hello world" />
        </div>
    );
}

export default App;


问:
Create an array of object properties for each item that has the same key
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

```<code>[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]
</code>```

becomes

```<code>[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]
</code>```

any ideas?

答:
we can also achieve this by using forEach loop :

const input = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const resultObj = {};
const resultArr = [];

input.forEach((obj) => {
  resultObj[Object.keys(obj)[0]] = [];
})

input.forEach((obj) => {
  resultObj[Object.keys(obj)[0]].push(obj[Object.keys(obj)[0]]);
  resultArr.push(resultObj);
})

console.log([...new Set(resultArr)]);```

Body:
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]

becomes

[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]

any ideas?


问:
ArrayList cannot be resolved to a type : What is error in this code?
I was creating an ArrayList, and i am getting following error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ArrayList cannot be resolved to a type
Please help.</p>
```<code>package learnCoreJava;

import java.util.List;

public class ArrayListDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Always initialize the concrete implementation with the interface types
                List<Integer> arrayList = new ArrayList<>(5);

                for(int i=0;i<=5;i++)
                    arrayList.add(i);

                System.out.println(arrayList);
    }

}
</code>```

答:
Add this import statement :-

import java.util.ArrayList;

Body:
I was creating an ArrayList, and i am getting following error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ArrayList cannot be resolved to a type
Please help.

package learnCoreJava;

import java.util.List;

public class ArrayListDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Always initialize the concrete implementation with the interface types
                List<Integer> arrayList = new ArrayList<>(5);

                for(int i=0;i<=5;i++)
                    arrayList.add(i);

                System.out.println(arrayList);
    }

}


问:
Rails - create a record with nested attribute
I'm receiving a request in the format:

{
  recipe_translations: [{
      "lang": "en",
      "name": "wow",
      "value": "test"
    }]
}
```
<p>The <code>Recipe</code>:</p>
<pre class="lang-rb prettyprint-override"><code>class Recipe < ApplicationRecord
  has_many :recipe_translations, dependent: :destroy
  accepts_nested_attributes_for :recipe_translations
end
</code>```

The controller:

class RecipesController < ApplicationController
  def create
    recipe = Recipe.new(recipe_params)
  end

  def recipe_params
    # whitelist params
    params.permit(recipe_translations: %i[lang name value])
  end

end
```
<p>Obviously, something is very wrong but not sure what. The error I'm getting is:</p>
```#<ActiveRecord::AssociationTypeMismatch: RecipeTranslation(#69020) expected, got {\"lang\"=>\"en\", \"name\"=>\"wow\", \"value\"=>\"test\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#52480)>
```

答:
You can use:</p>
```<code>def recipe_params
   params.fetch(:recipe_translations, {}).permit(%w[lang name value])
end
</code>```

Body:
I'm receiving a request in the format:

{
  recipe_translations: [{
      "lang": "en",
      "name": "wow",
      "value": "test"
    }]
}

The Recipe:

class Recipe < ApplicationRecord
  has_many :recipe_translations, dependent: :destroy
  accepts_nested_attributes_for :recipe_translations
end

The controller:

class RecipesController < ApplicationController
  def create
    recipe = Recipe.new(recipe_params)
  end

  def recipe_params
    # whitelist params
    params.permit(recipe_translations: %i[lang name value])
  end

end

Obviously, something is very wrong but not sure what. The error I'm getting is:

#<ActiveRecord::AssociationTypeMismatch: RecipeTranslation(#69020) expected, got {\"lang\"=>\"en\", \"name\"=>\"wow\", \"value\"=>\"test\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#52480)>

Body:
You can use:

def recipe_params
   params.fetch(:recipe_translations, {}).permit(%w[lang name value])
end


问:
Mock throwing of Exception with Android Coroutines
I am introducing coroutines to an android app I am working.  There is lots of legacy but I am now adding some new networking code and using coroutines for it.

EDIT
Updating to add the whole test

```<code>coEvery { service.getAddress(any(), any(), any()) } coAnswers { throw Exception("Test Exception") }
val subject = repository.getAddress(123, "en", null)

coVerify(exactly = 1) { service.getAddress(any(), any(), any())}
</code>```

So the line coEvery { service.getAddress(any(), any(), any()) } coAnswers { throw Exception("Test Exception") } in the test on it's own doesn't cause an issue.  It falls down when adding val subject = repository.getAddress(123, "en", null)

EDIT 2 TO INCLUDE REPO
Here is the repo:

```<code>class AddressRepository (
    val addressRestService: AddressRestService,
    val dispatcher: CoroutineDispatcher
){
    suspend fun getAddress(
        wlid: Int,
        locale: String?,
        googleAddressObject: GeoResponse?
    ) : AddressForm = withContext(dispatcher) {
             addressRestService.getAddress(wlid, locale, googleAddressObject)
    }
}

</code>```

I am using clean architecture and I am trying to test my repository.  I am using the Mockk lib and I am trying to test a failure.

Below is a snippet:

```<code>coEvery {
    service.getAddress(123, "en", null)
} throw Exception()
</code>```

When running the above I get test failure with the following stack trace:

```<code>java.lang.Exception
    at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invokeSuspend(AddressRepositoryTest.kt:52)
    at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invoke(AddressRepositoryTest.kt)
    at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91)
    at kotlinx.coroutines.BuildersKt.async(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
    at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:73)
    at at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false(AddressRepositoryTest.kt:49)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

</code>```

I have tried different variations e.g.

```<code>coEvery {
    service.getAddress(123, "en", null)
}.coAnswers {
    throw Exception()
}

</code>```

When running the above I get a test failure with the following stack trace:

```<code>java.lang.Exception
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1$2.invokeSuspend(AddressRepositoryTest.kt:53)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1$2.invoke(AddressRepositoryTest.kt)
    at io.mockk.MockKStubScope$coAnswers$1.invokeSuspend(API.kt:2112)
    at io.mockk.MockKStubScope$coAnswers$1.invoke(API.kt)
    at io.mockk.CoFunctionAnswer$answer$1.invokeSuspend(Answers.kt:33)
    at io.mockk.CoFunctionAnswer$answer$1.invoke(Answers.kt)
    at io.mockk.JvmCoroutineCall.callCoroutine(InternalPlatformDsl.kt:212)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.mockk.JvmCoroutineCall.callWithContinuation(InternalPlatformDsl.kt:217)
    at io.mockk.CoFunctionAnswer.answer(Answers.kt:34)
    at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:14)
    at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
    at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
    at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
    at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
    at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
    at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
    at io.mockk.proxy.jvm.advice.BaseAdvice.handle(BaseAdvice.kt:42)
    at io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyInterceptor.interceptNoSuper(JvmMockKProxyInterceptor.java:45)
    at **.****.******.data.api.AddressRestService$Subclass0.getAddress(Unknown Source)
    at **.****.******.data.repository.AddressRepository$getAddress$2.invokeSuspend(AddressRepository.kt:18)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.test.internal.TestMainDispatcher.dispatch(MainTestDispatcher.kt:35)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:170)
    at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)
    at **.****.******.data.repository.AddressRepository.getAddress(AddressRepository.kt:17)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invokeSuspend(AddressRepositoryTest.kt:56)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invoke(AddressRepositoryTest.kt)
    at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91)
    at kotlinx.coroutines.BuildersKt.async(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
    at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:73)
    at **.****.******.data.repository.AddressRepositoryTest.when getAddress is called, returns false(AddressRepositoryTest.kt:49)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

</code>```

I would very much appreciate if anyone could point out where I'm going wrong.. if it is possible to mock throwing an exception with coroutines.  Any tips appreciated

答:
You can try to use JUnit Jupiter library, it allows to test throwing Exceptions by using assertThrows method. For example if you want to test that service.getAddress() function throws some Exception under certain conditions you can test it like the following:

```<code>assertThrows<Exception> { service.getAddress(123, "en", null) }
</code>```

This assertion checks whether getAddress throws Exception exception. You can replace Exception with another type you want to test.

If you want to throw an Exception you can use throws infix function:

```<code>coEvery { service.getAddress(123, "en", null) } throws NullPointerException("Error occurred")
</code>```

I guess the error you get is happening due to incorrect return value. Please try to return AddressForm object instead of throwing an Exception:

```<code>coEvery { service.getAddress(any(), any(), any()) } returns AddressForm(...)
</code>```

Body:
I am introducing coroutines to an android app I am working.  There is lots of legacy but I am now adding some new networking code and using coroutines for it.

EDIT
Updating to add the whole test

coEvery { service.getAddress(any(), any(), any()) } coAnswers { throw Exception("Test Exception") }
val subject = repository.getAddress(123, "en", null)

coVerify(exactly = 1) { service.getAddress(any(), any(), any())}

So the line coEvery { service.getAddress(any(), any(), any()) } coAnswers { throw Exception("Test Exception") } in the test on it's own doesn't cause an issue.  It falls down when adding val subject = repository.getAddress(123, "en", null)

EDIT 2 TO INCLUDE REPO
Here is the repo:

class AddressRepository (
    val addressRestService: AddressRestService,
    val dispatcher: CoroutineDispatcher
){
    suspend fun getAddress(
        wlid: Int,
        locale: String?,
        googleAddressObject: GeoResponse?
    ) : AddressForm = withContext(dispatcher) {
             addressRestService.getAddress(wlid, locale, googleAddressObject)
    }
}

I am using clean architecture and I am trying to test my repository.  I am using the Mockk lib and I am trying to test a failure.

Below is a snippet:

coEvery {
    service.getAddress(123, "en", null)
} throw Exception()

When running the above I get test failure with the following stack trace:

java.lang.Exception
    at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invokeSuspend(AddressRepositoryTest.kt:52)
    at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invoke(AddressRepositoryTest.kt)
    at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91)
    at kotlinx.coroutines.BuildersKt.async(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
    at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:73)
    at at **.*******.data.repository.AddressRepositoryTest$when getAddress is called, returns false(AddressRepositoryTest.kt:49)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

I have tried different variations e.g.

coEvery {
    service.getAddress(123, "en", null)
}.coAnswers {
    throw Exception()
}

When running the above I get a test failure with the following stack trace:

java.lang.Exception
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1$2.invokeSuspend(AddressRepositoryTest.kt:53)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1$2.invoke(AddressRepositoryTest.kt)
    at io.mockk.MockKStubScope$coAnswers$1.invokeSuspend(API.kt:2112)
    at io.mockk.MockKStubScope$coAnswers$1.invoke(API.kt)
    at io.mockk.CoFunctionAnswer$answer$1.invokeSuspend(Answers.kt:33)
    at io.mockk.CoFunctionAnswer$answer$1.invoke(Answers.kt)
    at io.mockk.JvmCoroutineCall.callCoroutine(InternalPlatformDsl.kt:212)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.mockk.JvmCoroutineCall.callWithContinuation(InternalPlatformDsl.kt:217)
    at io.mockk.CoFunctionAnswer.answer(Answers.kt:34)
    at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:14)
    at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
    at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
    at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
    at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
    at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
    at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
    at io.mockk.proxy.jvm.advice.BaseAdvice.handle(BaseAdvice.kt:42)
    at io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyInterceptor.interceptNoSuper(JvmMockKProxyInterceptor.java:45)
    at **.****.******.data.api.AddressRestService$Subclass0.getAddress(Unknown Source)
    at **.****.******.data.repository.AddressRepository$getAddress$2.invokeSuspend(AddressRepository.kt:18)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.test.internal.TestMainDispatcher.dispatch(MainTestDispatcher.kt:35)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:170)
    at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)
    at **.****.******.data.repository.AddressRepository.getAddress(AddressRepository.kt:17)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invokeSuspend(AddressRepositoryTest.kt:56)
    at **.****.******.data.repository.AddressRepositoryTest$when getAddress is called, returns false$1.invoke(AddressRepositoryTest.kt)
    at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)
    at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91)
    at kotlinx.coroutines.BuildersKt.async(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
    at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:73)
    at **.****.******.data.repository.AddressRepositoryTest.when getAddress is called, returns false(AddressRepositoryTest.kt:49)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

I would very much appreciate if anyone could point out where I'm going wrong.. if it is possible to mock throwing an exception with coroutines.  Any tips appreciated

Body:
You can try to use JUnit Jupiter library, it allows to test throwing Exceptions by using assertThrows method. For example if you want to test that service.getAddress() function throws some Exception under certain conditions you can test it like the following:

assertThrows<Exception> { service.getAddress(123, "en", null) }

This assertion checks whether getAddress throws Exception exception. You can replace Exception with another type you want to test.

If you want to throw an Exception you can use throws infix function:

coEvery { service.getAddress(123, "en", null) } throws NullPointerException("Error occurred")

I guess the error you get is happening due to incorrect return value. Please try to return AddressForm object instead of throwing an Exception:

coEvery { service.getAddress(any(), any(), any()) } returns AddressForm(...)