问:
How to align items above and below each other within one flexbox?
I'm currently trying to align the number 238,741 and the letter N in Number. Currently I have a padding between the Prize Pool div and the Number Active div. They're all contained within a parent with display set to flex and flex-direction: column. They're then within another parent container with display flex and direction set to row. I tried setting different paddings between the divs but when I zoom in or out they don't maintain their position.

I cannot figure out how to make them align and stay aligned when zooming in and out or going into mobile view. I've spent 7 hours on it and made little progress by going through CSS tricks.

Code:

```<code>  <Wrapper>
    <HeaderWrapper row alignItems="center">
      <PrizeText variant={TextVariant.subhead}>Prize Pool</PrizeText>
      <Text color={TextColor.primary} fontWeight="600" variant={TextVariant.subhead}>Number Active</Text>
      <GoldText style={{'padding-right': '26%'}} variant={TextVariant.display}>$7,162,245</GoldText>
      <GoldText color={TextColor.primary} variant={TextVariant.display}>238,741</GoldText>
    </HeaderWrapper>
  </Wrapper>
</code>```

```<code>const HeaderWrapper = styled(Box)`
  height: auto;
  align-items: flex-start;
  /* border: 2px solid white; */
  flex-wrap: wrap;
  margin-top: 45px;
  margin-left: 32px;

`;
const MoneyWrapper = styled(Box)`
  height: auto;
  align-items: flex-start;
  /* border: 2px solid white; */
  flex-wrap: wrap;
  margin-left: 32px;

`;

const GoldText = styled(Text)`
  background-image: linear-gradient(98.84deg, #C9882B 0%, #E7CA66 47.71%, #C69935 100%);
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  white-space: nowrap;
`;

const PrizeText = styled(Text)`
  padding-right: 152px;
  color: ${props => props.theme.palette.text.primary};
  font-weight: 600;
  white-space: nowrap;
`;

const Wrapper = styled(Box)`
  position: relative;
  border: 2px solid white;
  width: 100%;
  /* justify-content: center; */
  align-items: center;
`;

</code>```

A Box is just a div, with display set to flex and can take the prop col or row to change the flex direction.

答:
It might help to rethink the structure of your components. If you wrap <PrizeText> and <GoldText> in a container and <Text> and <GoldText> in another container then things will fall into place for you.

Kind of like this:

.wrapper {
  display: flex;
  justify-content: space-around;
  padding: 1rem;
}

.missing-wrapper {
  width: 50%;
}

h1, h5, div {
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="missing-wrapper">
    <h5>Prize Pool</h5>
    <h1>$7,162,245</h1>
  </div>
  <div class="missing-wrapper">
    <h5>Number Active</h5>
    <h1>238,741</h1>
  </div>
</div></code>```

Body:
I'm currently trying to align the number 238,741 and the letter N in Number. Currently I have a padding between the Prize Pool div and the Number Active div. They're all contained within a parent with display set to flex and flex-direction: column. They're then within another parent container with display flex and direction set to row. I tried setting different paddings between the divs but when I zoom in or out they don't maintain their position.

I cannot figure out how to make them align and stay aligned when zooming in and out or going into mobile view. I've spent 7 hours on it and made little progress by going through CSS tricks.

Code:

  <Wrapper>
    <HeaderWrapper row alignItems="center">
      <PrizeText variant={TextVariant.subhead}>Prize Pool</PrizeText>
      <Text color={TextColor.primary} fontWeight="600" variant={TextVariant.subhead}>Number Active</Text>
      <GoldText style={{'padding-right': '26%'}} variant={TextVariant.display}>$7,162,245</GoldText>
      <GoldText color={TextColor.primary} variant={TextVariant.display}>238,741</GoldText>
    </HeaderWrapper>
  </Wrapper>

const HeaderWrapper = styled(Box)`
  height: auto;
  align-items: flex-start;
  /* border: 2px solid white; */
  flex-wrap: wrap;
  margin-top: 45px;
  margin-left: 32px;

`;
const MoneyWrapper = styled(Box)`
  height: auto;
  align-items: flex-start;
  /* border: 2px solid white; */
  flex-wrap: wrap;
  margin-left: 32px;

`;

const GoldText = styled(Text)`
  background-image: linear-gradient(98.84deg, #C9882B 0%, #E7CA66 47.71%, #C69935 100%);
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  white-space: nowrap;
`;

const PrizeText = styled(Text)`
  padding-right: 152px;
  color: ${props => props.theme.palette.text.primary};
  font-weight: 600;
  white-space: nowrap;
`;

const Wrapper = styled(Box)`
  position: relative;
  border: 2px solid white;
  width: 100%;
  /* justify-content: center; */
  align-items: center;
`;

A Box is just a div, with display set to flex and can take the prop col or row to change the flex direction.

Body:
It might help to rethink the structure of your components. If you wrap <PrizeText> and <GoldText> in a container and <Text> and <GoldText> in another container then things will fall into place for you.

Kind of like this:

.wrapper {
  display: flex;
  justify-content: space-around;
  padding: 1rem;
}

.missing-wrapper {
  width: 50%;
}

h1, h5, div {
  border: 1px solid red;
}

<div class="wrapper">
  <div class="missing-wrapper">
    <h5>Prize Pool</h5>
    <h1>$7,162,245</h1>
  </div>
  <div class="missing-wrapper">
    <h5>Number Active</h5>
    <h1>238,741</h1>
  </div>
</div>


来源: stackexchange

问:
Visual Studio Rebuilds unmodified projects sometimes after a PC reboot
I've a Visual Studio 2013 solution with about 50 C# projects. Normally if I select build (F6) it just builds the projects which have changed. But sometimes after a I shut down and restart my PC it rebuilds all when I select build (F6). Why?

This doesn't happen all the time when I restart my PC. Most of the times it says that all projects are up to date after a reboot. But sometimes it rebuilds all.

I took a look at the following question Visual Studio Rebuilds unmodified projects and its answers.

The next step I did was to set the build output verbosity to diagnostic.

I'm getting the following output when Visual Studio rebuilds all after a PC restart:

```<code>1>Project 'Project1' is not up to date. Missing input file
...
</code>```

There much more lines (more than 1000). I took a look at them but I still don't understand why Visual Studio rebuilds the project.

Update

Why does Visual Studio needs the following file?

```<code>1>Project 'Project1' is not up to date. Missing input file
'c:\users\wo\appdata\local\temp\.netframework,version=v4.5.assemblyattributes.cs'.
...
</code>```

答:
For future travelers, I think it's also just a bug in current versions of Visual Studio 2019, 16.6 and newer.

This problem happens for me with Visual Studio 2019 versions 16.6.0 and 16.6.1. I have cross-version aware C# projects that do not have this issue for 2010, 2015, 2017, or 2019 16.5 and older, on the same machine and same user, with the same project in the same folder and solution.

With the recent 2019 versions (in the last month or so, May and June 1st 2020) I get similar message:

1>Project 'Banana' is not up to date. Missing input file 'c:\users\banana\appdata\local\temp.netframework,version=v4.7.2.assemblyattributes.cs'.

If I clean then build, then its normal. If I run a successive build I get the error.

This happens with or without reboot, and after cleaning temp folders even, or if I run Visual Studio with admin or not. The path its trying to find really exists, and pops up if paste in explorer.

I've completely cleaned all but the code files with fresh folders and have the same issue. For me it's only with C# projects. So I think it's a 16.6 bug.

See recent changes:

KirillOsenkov commented on Jan 4 2020

@livarcocc would it be possible to prioritize this? This is an impactful issue that's very easy to fix and has been open for three years now. Seems like low-hanging fruit.

bording commented on Feb 12 2020

With the fix for this being merged into master now, which release will it be a part of? I see that this issue is on the 16.5 milestone, so does that mean it will be in that release, or does the fix also need to be ported to another branch?

tmat commented on Feb 12 2020

@bording I updated the milestone to 16.6 as I believe master is 16.6.

https://github.com/microsoft/msbuild/issues/1479

ContentLicense: CC BY-SA 4.0

Body:
I've a Visual Studio 2013 solution with about 50 C# projects. Normally if I select build (F6) it just builds the projects which have changed. But sometimes after a I shut down and restart my PC it rebuilds all when I select build (F6). Why?

This doesn't happen all the time when I restart my PC. Most of the times it says that all projects are up to date after a reboot. But sometimes it rebuilds all.

I took a look at the following question Visual Studio Rebuilds unmodified projects and its answers.

The next step I did was to set the build output verbosity to diagnostic.

I'm getting the following output when Visual Studio rebuilds all after a PC restart:

1>Project 'Project1' is not up to date. Missing input file
...

There much more lines (more than 1000). I took a look at them but I still don't understand why Visual Studio rebuilds the project.

Update

Why does Visual Studio needs the following file?

1>Project 'Project1' is not up to date. Missing input file
'c:\users\wo\appdata\local\temp\.netframework,version=v4.5.assemblyattributes.cs'.
...


问:
Why does this list return [False, False, 3, True]?
I've been working through an exercise on Kaggle and was tasked with: Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise.

```<code>L = [1, 2, 3, 4]
LL = L
for nums in L:
    if L[nums] > 2:
        LL[nums] = True
    else:
        LL[nums] = False
print(LL)
</code>```

That is what I came up with but it prints the list [False, False, 3, True]. Also, I replaced the variable "thresh" with the number 2 and added a print instead of a return statement since it's not a function. I'm guessing that this result is because when it hits the 3 or the number in index #2 in the list it for some reason skips over it and I cannot seem to figure out why?

答:
Problem:

Your for loop is wrong. You are using nums as if it were an index in the array; the problem is that the in keyword in Python gives you the actual items from the list, which in this case are the numbers themselves. For example:

```<code>my_list = [5,3,1,6]
for num in my_list:
    print(num)
# prints 5,3,1,6
</code>```

Also, you should create a deep copy of the original list so that you don't overwrite the original list:

```<code>LL = L.copy()
</code>```

Hint: if based on this, you understand what's wrong, try to implement it correctly before reading the solution below!

Solution:

The correct way to implement this:

```<code>L = [1, 2, 3, 4]
LL = L.copy() # this creates an actual copy, not just a reference
for i in range(len(L)):
    if L[i] > 2:
        LL[i] = True
    else:
        LL[i] = False
print(LL)
</code>```

Body:
I've been working through an exercise on Kaggle and was tasked with: Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise.

L = [1, 2, 3, 4]
LL = L
for nums in L:
    if L[nums] > 2:
        LL[nums] = True
    else:
        LL[nums] = False
print(LL)

That is what I came up with but it prints the list [False, False, 3, True]. Also, I replaced the variable "thresh" with the number 2 and added a print instead of a return statement since it's not a function. I'm guessing that this result is because when it hits the 3 or the number in index #2 in the list it for some reason skips over it and I cannot seem to figure out why?

Body:
Problem:

Your for loop is wrong. You are using nums as if it were an index in the array; the problem is that the in keyword in Python gives you the actual items from the list, which in this case are the numbers themselves. For example:

my_list = [5,3,1,6]
for num in my_list:
    print(num)
# prints 5,3,1,6

Also, you should create a deep copy of the original list so that you don't overwrite the original list:

LL = L.copy()

Hint: if based on this, you understand what's wrong, try to implement it correctly before reading the solution below!

Solution:

The correct way to implement this:

L = [1, 2, 3, 4]
LL = L.copy() # this creates an actual copy, not just a reference
for i in range(len(L)):
    if L[i] > 2:
        LL[i] = True
    else:
        LL[i] = False
print(LL)


问:
How to solve a problem time expired in javasrcipt
I am trying to send data to Google Sheet in my mobile application.

The data arrives well but the code does not return the result quickly
here is my JavaScript code.

The problem is that it takes a long time (around 360s) to return the result

it's ok

```<code>var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/177kUZc61U8huVsq2OcGsiF2OGdPCSxMjkoh2C4KIWPM/edit#gid=0");
var sheet = ss.getSheetByName('Info');

function doGet(e) {
    var action = e.parameter.action;

    if (action == 'UpdateInfo') {

        //return UpdateInfo(e);
    }
}

function doPost(e) {
    var action = e.parameter.action;

    if (action == 'UpdateInfo') {
        return UpdateInfo(e);
    }
}

function UpdateInfo(e) {
    var values = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
    var email = e.parameter.email;
    var password = e.parameter.password;
    //var date = sheet.getRange('A').getValues();//new Date();
    var name = e.parameter.name; ///Item1
    var lname = e.parameter.lname;
    var itemuserImage = e.parameter.itemuserImage;
    var region = e.parameter.region;
    var provaince = e.parameter.provaince;
    var ecole = e.parameter.ecole;
    var Unite = e.parameter.unite;
    var niveau = e.parameter.niveau;
    //var flag = 0;
    var lr = sheet.getLastRow();

    for (var i = 1; i <= lr; i++) {
        var IDuser = sheet.getRange(i, 1).getValue();

        //row[1];
        var shetemail=sheet.getRange(i,2).getValue();
        var shetpassword=sheet.getRange(i,3).getValue();

        if (shetpassword==password && shetemail==email ) {
            sheet.getRange(i,4).setValue(name);
            // sheet.getRange(i,5).setValue(lname);
            //row[2];
            ///zoydghnmayad sheet.getRange(i,7).setValue(region);
            //row[4];
            sheet.getRange(i,8).setValue(provaince);
            //row[5];
            sheet.getRange(i,9).setValue(ecole);
            //row[5];
            sheet.getRange(i,10).setValue(Unite);
            //row[5];
            sheet.getRange(i,11).setValue(niveau);
            //row[5];
            var dropbox="USERSIMAGE prof";
            var folder, folders=DriveApp.getFoldersByName(dropbox);
            if (folders.hasNext()) {
                folder=folders.next();
            } else {
                folder=DriveApp.createFolder(dropbox);
            }
            var fileName=IDuser+"profile_pic.jpg";
            var contentType="image/jpg" , bytes=Utilities.base64Decode(itemuserImage), blob=Utilities.newBlob(bytes, contentType,fileName);
            var file=folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK,DriveApp.Permission.VIEW);
            var fileIdumage=file.getId();
            var fileUrlumage="https://drive.google.com/uc?export=view&id=" +fileIdumage; sheet.getRange(i,6).setValue(fileUrlumage);
            //row[5];
            return ContentService.createTextOutput("its ok").setMimeType(ContentService.MimeType.TEXT);
        }
    } ///thiya loop
}
</code>```

答:
Not quite sure.But do you check your image size of "profile_pic.jpg".
In my experience,if you capture the profile image using mobile app camera,the image size is extremely large.It will take ages to upload the image if you forget to compress it(no need such high HD image for profile, and compression is neccesary).

As a matter of that,please double check size of the image you were uploading.And please do not forget to compress it if it occupy too much space.

Body:
I am trying to send data to Google Sheet in my mobile application.

The data arrives well but the code does not return the result quickly
here is my JavaScript code.

The problem is that it takes a long time (around 360s) to return the result

it's ok

var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/177kUZc61U8huVsq2OcGsiF2OGdPCSxMjkoh2C4KIWPM/edit#gid=0");
var sheet = ss.getSheetByName('Info');

function doGet(e) {
    var action = e.parameter.action;

    if (action == 'UpdateInfo') {

        //return UpdateInfo(e);
    }
}

function doPost(e) {
    var action = e.parameter.action;

    if (action == 'UpdateInfo') {
        return UpdateInfo(e);
    }
}

function UpdateInfo(e) {
    var values = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
    var email = e.parameter.email;
    var password = e.parameter.password;
    //var date = sheet.getRange('A').getValues();//new Date();
    var name = e.parameter.name; ///Item1
    var lname = e.parameter.lname;
    var itemuserImage = e.parameter.itemuserImage;
    var region = e.parameter.region;
    var provaince = e.parameter.provaince;
    var ecole = e.parameter.ecole;
    var Unite = e.parameter.unite;
    var niveau = e.parameter.niveau;
    //var flag = 0;
    var lr = sheet.getLastRow();

    for (var i = 1; i <= lr; i++) {
        var IDuser = sheet.getRange(i, 1).getValue();

        //row[1];
        var shetemail=sheet.getRange(i,2).getValue();
        var shetpassword=sheet.getRange(i,3).getValue();

        if (shetpassword==password && shetemail==email ) {
            sheet.getRange(i,4).setValue(name);
            // sheet.getRange(i,5).setValue(lname);
            //row[2];
            ///zoydghnmayad sheet.getRange(i,7).setValue(region);
            //row[4];
            sheet.getRange(i,8).setValue(provaince);
            //row[5];
            sheet.getRange(i,9).setValue(ecole);
            //row[5];
            sheet.getRange(i,10).setValue(Unite);
            //row[5];
            sheet.getRange(i,11).setValue(niveau);
            //row[5];
            var dropbox="USERSIMAGE prof";
            var folder, folders=DriveApp.getFoldersByName(dropbox);
            if (folders.hasNext()) {
                folder=folders.next();
            } else {
                folder=DriveApp.createFolder(dropbox);
            }
            var fileName=IDuser+"profile_pic.jpg";
            var contentType="image/jpg" , bytes=Utilities.base64Decode(itemuserImage), blob=Utilities.newBlob(bytes, contentType,fileName);
            var file=folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK,DriveApp.Permission.VIEW);
            var fileIdumage=file.getId();
            var fileUrlumage="https://drive.google.com/uc?export=view&id=" +fileIdumage; sheet.getRange(i,6).setValue(fileUrlumage);
            //row[5];
            return ContentService.createTextOutput("its ok").setMimeType(ContentService.MimeType.TEXT);
        }
    } ///thiya loop
}


问:
How to apply decorators to lambdas?
Is there any syntax for using a decorator on a lambda function in Python? Example:

```<code>def simpledecorator(f):
     def new_f():
         print "Using a decorator: "
         f()
     return  new_f

@simpledecorator
def hello():
    print "Hello world!"
</code>```

Results in this output:

>>> hello()
Using a simple decorator:
Hello world!
```

<p>Yet when I try the same with a lambda:</p>

```@anotherdecorator
f = lambda x: x * 2
```

<p>I get this:</p>

<pre class="lang-none prettyprint-override"><code>  File "<stdin", line 2
    f = lambda x: x * 2
    ^
 SyntaxError: invalid syntax
</code>```

I feel like this might be a good way to make lambdas more versatile by allowing statements to be "injected" into them. But if there exists such a feature, I don't know what the syntax is.

答:
There appear to be two options which give the functionality, but without the clean syntax:

(1) Keep lambda and ditch the decorator syntax (as posted by dan04):

f = simpledecorator( lambda : print( "Hello World" ) )

(2) Keep the decorator syntax and use a 1 line def statement instead of lambda:

```<code>@simpledecorator
def f(): print ( "Hello World" )

</code>```

This 2nd form may be preferable if you want to chain decorators:

```<code>@simpledecorator
@simpledecorator
def f(): print ( "Hello World" )

</code>```

ContentLicense: CC BY-SA 3.0

Title: How to apply decorators to lambdas?

Body:
Is there any syntax for using a decorator on a lambda function in Python? Example:

def simpledecorator(f):
     def new_f():
         print "Using a decorator: "
         f()
     return  new_f

@simpledecorator
def hello():
    print "Hello world!"

Results in this output:

>>> hello()
Using a simple decorator:
Hello world!

Yet when I try the same with a lambda:

@anotherdecorator
f = lambda x: x * 2

I get this:

  File "<stdin", line 2
    f = lambda x: x * 2
    ^
 SyntaxError: invalid syntax

I feel like this might be a good way to make lambdas more versatile by allowing statements to be "injected" into them. But if there exists such a feature, I don't know what the syntax is.

Body:
There appear to be two options which give the functionality, but without the clean syntax:

(1) Keep lambda and ditch the decorator syntax (as posted by dan04):

f = simpledecorator( lambda : print( "Hello World" ) )

(2) Keep the decorator syntax and use a 1 line def statement instead of lambda:

@simpledecorator
def f(): print ( "Hello World" )

This 2nd form may be preferable if you want to chain decorators:

@simpledecorator
@simpledecorator
def f(): print ( "Hello World" )


问:
issue accessing elements of hash in perl
I have the below hash:

```<code>my %releaseMap = {"rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 };
</code>```

I want to get the values rel1.2.3 and rel2.4 in the variable $rel, I want to get the values lnx86 and lnppc in $port and I want to get the value DEV in $branch.

I am new to the Hash concept in perl, I am not able to figure out how this can be done.

Can someone please help. Thanks

答:
Assuming you really have

```<code>my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );
</code>```

You can use

```<code>for my $rel_id (keys(%releaseMap)) {
   my $rel = $releaseMap{$rel_id};

   my $ports    = $rel->{supporedPorts};
   my $branches = $rel->{branch};

   say "[$rel_id] ports = @$ports; branches = @$branches";
}
</code>```

Docs:

perlreftut

perllol

Body:
I have the below hash:

my %releaseMap = {"rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 };

I want to get the values rel1.2.3 and rel2.4 in the variable $rel, I want to get the values lnx86 and lnppc in $port and I want to get the value DEV in $branch.

I am new to the Hash concept in perl, I am not able to figure out how this can be done.

Can someone please help. Thanks

Body:
Assuming you really have

my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );

You can use

for my $rel_id (keys(%releaseMap)) {
   my $rel = $releaseMap{$rel_id};

   my $ports    = $rel->{supporedPorts};
   my $branches = $rel->{branch};

   say "[$rel_id] ports = @$ports; branches = @$branches";
}

Docs:

perlreftut

perllol


问:
How do I do an IF in Microsoft SQL SELECT query?
I am an absolute beginner in SQL.
Example:
I want to do a query to select people whose names begin with X if the result is 0, I want to select people whose names begin with Y.

How do I do this? Thanks.

答:
Here's a set-based solution:</p>

```<code>SELECT *
  FROM table
 WHERE NAME LIKE 'X%'
UNION
SELECT *
  FROM table
 WHERE NAME LIKE 'Y%'
       AND NOT EXISTS (
                       SELECT *
                         FROM table AS T1
                        WHERE T1.NAME LIKE 'X%'
                      );
</code>```

Body:
Here's a set-based solution:

SELECT *
  FROM table
 WHERE NAME LIKE 'X%'
UNION
SELECT *
  FROM table
 WHERE NAME LIKE 'Y%'
       AND NOT EXISTS (
                       SELECT *
                         FROM table AS T1
                        WHERE T1.NAME LIKE 'X%'
                      );


问:
Where should I call a method to use data from it?
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          hello
        </div>
      </>
    );
  }
}

export default Albums;

</code>```

I wanna do something like this inside the div.

```<code>this.state.albums.map((album) => (<AlbumCard img={album.img}/>))
</code>```

答:
componentDidMount() is the best place for making AJAX requests.

The componentDidMount() method will set state after the AJAX call fetches data. It will cause render() to be triggered when data is available.

Here is the working example with componentDidMount()

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props)
    this.state = { albums: [] }
  }

  componentDidMount() {
      axios.get(
                `http://localhost:4000/albums/${encodeURIComponent(this.props.id)}`,
                { params: { id: this.props.id } }
            )
           .then(response => {
                  console.log(`Returned album data from the server: ${res}`)
                  this.setState({ albums: response.data })
                }
            )
           .catch(e => {
                   console.log("Connection failure: " + e)
                }
           )
  }

  render() {
    return (
        <div>
            {/*   Code for {this.state.albums.map(item => )}  */}
            {/*   render() method will be called whenever state changes.*/}
            {/*   componentDidMount() will trigger render() when data is ready.*/}
        </div>
    )
  }
}

export default Albums
</code>```

More information:

https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/

Body:
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>

          hello

      </>
    );
  }
}

export default Albums;

I wanna do something like this inside the div.

this.state.albums.map((album) => (<AlbumCard img={album.img}/>))

Body:
componentDidMount() is the best place for making AJAX requests.

The componentDidMount() method will set state after the AJAX call fetches data. It will cause render() to be triggered when data is available.

Here is the working example with componentDidMount()

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props)
    this.state = { albums: [] }
  }

  componentDidMount() {
      axios.get(
                `http://localhost:4000/albums/${encodeURIComponent(this.props.id)}`,
                { params: { id: this.props.id } }
            )
           .then(response => {
                  console.log(`Returned album data from the server: ${res}`)
                  this.setState({ albums: response.data })
                }
            )
           .catch(e => {
                   console.log("Connection failure: " + e)
                }
           )
  }

  render() {
    return (
        <div>
            {/*   Code for {this.state.albums.map(item => )}  */}
            {/*   render() method will be called whenever state changes.*/}
            {/*   componentDidMount() will trigger render() when data is ready.*/}
        </div>
    )
  }
}

export default Albums

More information:

https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/


问:
Mysterious error when accessing BRENDA with zeep
I'm trying to get all human Kcats and KMs from BRENDA using SOAP (technically zeep with Python3 I guess). I used this code, which follows the example code given here:

```<code>from zeep import Client
import hashlib

wsdl = "https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl"
password = hashlib.sha256("password".encode("utf-8")).hexdigest()
client = Client(wsdl)
parameters = (
    "email@email.com",
    password,
    "organism*Homo sapiens"
)
resultString = client.service.getKcatKmValue(*parameters)
</code>```

and it gives me the error "Missing element organism (getKcatKmValue.organism)"

It's not clear to me what I'm doing wrong. Any insight would be appreciated.

答:
If you run this command to inspect the definition of methods/operations:
python -mzeep https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl

you can see the definition of getKcatKmValue as follows:

```<code>getKcatKmValue(email: xsd:string, password: xsd:string, ecNumber: xsd:string, organism: xsd:string, kcatKmValue: xsd:string, kcatKmValueMaximum: xsd:string, substrate: xsd:string, commentary: xsd:string, ligandStructureId: xsd:string, literature: xsd:string) -> return: ns0:ArrayOfKcatKmValues
</code>```

so all of these parameters must be supplied which you are not passing in parameters hence the error.

a dict can also be passed to operation for a better visibility of passed arguments like this:

```<code>parameters = {
    'email': "email@email.com",
    'password': password,
    'ecNumber': ecNumber,
    'organism': "organism*Homo sapiens",
    'kcatKmValue': kcatKmValue,
    'kcatKmValueMaximum': kcatKmValueMaximum,
    'substrate': substrate,
    'commentary': commentary,
    'ligandStructureId': ligandStructureId,
    'literature' : literature
}

# then pass dict as follows:
resultString = client.service.getKcatKmValue(**parameters)
</code>```

hope this helps.

Body:
I'm trying to get all human Kcats and KMs from BRENDA using SOAP (technically zeep with Python3 I guess). I used this code, which follows the example code given here:

from zeep import Client
import hashlib

wsdl = "https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl"
password = hashlib.sha256("password".encode("utf-8")).hexdigest()
client = Client(wsdl)
parameters = (
    "email@email.com",
    password,
    "organism*Homo sapiens"
)
resultString = client.service.getKcatKmValue(*parameters)

and it gives me the error "Missing element organism (getKcatKmValue.organism)"

It's not clear to me what I'm doing wrong. Any insight would be appreciated.

Body:
If you run this command to inspect the definition of methods/operations:
python -mzeep https://www.brenda-enzymes.org/soap/brenda_zeep.wsdl

you can see the definition of getKcatKmValue as follows:

getKcatKmValue(email: xsd:string, password: xsd:string, ecNumber: xsd:string, organism: xsd:string, kcatKmValue: xsd:string, kcatKmValueMaximum: xsd:string, substrate: xsd:string, commentary: xsd:string, ligandStructureId: xsd:string, literature: xsd:string) -> return: ns0:ArrayOfKcatKmValues

so all of these parameters must be supplied which you are not passing in parameters hence the error.

a dict can also be passed to operation for a better visibility of passed arguments like this:

parameters = {
    'email': "email@email.com",
    'password': password,
    'ecNumber': ecNumber,
    'organism': "organism*Homo sapiens",
    'kcatKmValue': kcatKmValue,
    'kcatKmValueMaximum': kcatKmValueMaximum,
    'substrate': substrate,
    'commentary': commentary,
    'ligandStructureId': ligandStructureId,
    'literature' : literature
}

# then pass dict as follows:
resultString = client.service.getKcatKmValue(**parameters)

hope this helps.


问:
not able to revise paypal subscription
I am trying to upgrade the plan of paypal subscription using Rest API.

https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_revise

This is the documentation I am following.

But I am getting the following error :

{"name":"UNPROCESSABLE_ENTITY","message":"The requested action could
  not be performed, semantically incorrect, or failed business
  validation.","debug_id":"9d40b8cfc8e6e","details":[{"issue":"PAYMENT_IN_PROGRESS","description":"Payment
  for the subscription is in
  progress."}],"links":[{"href":"https://developer.paypal.com/docs/api/v1/billing/subscriptions#UNPROCESSABLE_ENTITY","rel":"information_link","method":"GET"}]}

What Am I doing wrong as this subscription is active with 1 Day of recurring frequency

答: You should attempt to revise a subscription on a day when there is no payment in progress. For this to be possible, create a subscription that recurs less rapidly than every day.</p>

Title: not able to revise paypal subscription


问:
Attach PDF document including text and image to Email C# Windows Application
I am working on email sending module in which i have to add normal string text and following to that a barcode image data and should be attach as PDF type. But pdf is coming as shown below

some text here
......
text ends

```<code><img
src='data:image/png;base64,Qk1mZgAAAAAAADYAAAAoAAAA2gAAAB4AAAABAC..... alt='img'>
</code>```

see my code below,

```<code>MailMessage message = new MailMessage();
attachmentName = "invoice";
attachmentBody = new MemoryStream(att.Value); // byte[] format
string attachmentTypeTmp = "PDF"
attach = mailProxy.AttachReceipt(attachmentTypeTmp, attachmentName, attachmentBody);
//add attachment to mail message
message.Attachments.Add(attach);
</code>```

答:
try using System.Net.Mail.Attcachment to set the conenttype to pdf. also you could use the using statement for the MemoryStream like this. With using the memory stream is automatically disposed afterwars and you don't need to by yourself.

using(MemoryStream ms = new MemoryStream(att.Value) {
 Attachment at = new Attachment(ms, new ContentType("application/pdf"));
 at.ContentDisposition.FileName = "invoice.pdf";
 message.Attachments.Add(at);

//send inside using or you get an exception from the stream
smtp.send(message)
}

```

Body:
I am working on email sending module in which i have to add normal string text and following to that a barcode image data and should be attach as PDF type. But pdf is coming as shown below

some text here
......
text ends

see my code below,

MailMessage message = new MailMessage();
attachmentName = "invoice";
attachmentBody = new MemoryStream(att.Value); // byte[] format
string attachmentTypeTmp = "PDF"
attach = mailProxy.AttachReceipt(attachmentTypeTmp, attachmentName, attachmentBody);
//add attachment to mail message
message.Attachments.Add(attach);


问:
Custom Dropdown arrow click issue
I am trying to replace the default select box arrow with a font awesome icon. Its styled as I want but when I click on the custom arrow, the dropdown does not open. If i click anywhere else on the select box, things work fine. I have set the z-index of the select box to be higher than that of the arrow. Not sure what the issue is.

body {
  padding: 30px;
}

.dropdown {
  position: relative;
  width: 300px;
}
.dropdown select {
  outline: none;
  margin: 0;
  padding: 0;
  border: none;
  border-radius: 0;
  box-shadow: none;
  background: none;
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  border-bottom: 1px solid;
  padding: 0 6px 0 6px;
  cursor: pointer;
  width: 100%;
  z-index: 2;
}
.dropdown select:hover {
  border-color: rgba(221, 221, 221, 0.5);
  background: rgba(221, 221, 221, 0.5);
}
.dropdown::after {
  position: absolute;
  font-family: "FontAwesome";
  color: black;
  content: "\f107";
  bottom: 1px;
  right: 4px;
}
.dropdown:hover::after {
  color: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="dropdown">
  <select id="exampleSelect1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
</div></code>```

答:
This worked for me:</p>

```<code>.select-field select {
    position: relative;
    z-index: 2;
}
</code>```

Title: Custom Dropdown arrow click issue

Body:
I am trying to replace the default select box arrow with a font awesome icon. Its styled as I want but when I click on the custom arrow, the dropdown does not open. If i click anywhere else on the select box, things work fine. I have set the z-index of the select box to be higher than that of the arrow. Not sure what the issue is.

body {
  padding: 30px;
}

.dropdown {
  position: relative;
  width: 300px;
}
.dropdown select {
  outline: none;
  margin: 0;
  padding: 0;
  border: none;
  border-radius: 0;
  box-shadow: none;
  background: none;
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  border-bottom: 1px solid;
  padding: 0 6px 0 6px;
  cursor: pointer;
  width: 100%;
  z-index: 2;
}
.dropdown select:hover {
  border-color: rgba(221, 221, 221, 0.5);
  background: rgba(221, 221, 221, 0.5);
}
.dropdown::after {
  position: absolute;
  font-family: "FontAwesome";
  color: black;
  content: "\f107";
  bottom: 1px;
  right: 4px;
}
.dropdown:hover::after {
  color: gray;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>

  <select id="exampleSelect1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>

Body:
This worked for me:

.select-field select {
    position: relative;
    z-index: 2;
}


问:
What are the advantages of using bundles in iPhone development?
What is the advantage of using bundle during iPhone development?

p.s. I see many SDK like Facebook SDK, Three20 are using bundles to contain images and other contents, but I am not sure why should I do so. What is the difference between using main bundle and a newly created bundle?

答: It's quite simple really. You use bundles just like you would use name spaces. Files in the newly created bundle could have files with the same names as files in the main bundle. Facebook SDK and Three20 have their own bundles, so that you can have any files you want in the main bundle without risking conflicts.</p>


问:
Back-End (JVM) internal error. Why do i get this IDE error but others with the same code do not?
I'm part of a group that is developing a program in Kotlin. I have recently pulled fresh code off the development branch. The problem is i get this strange error. I am the only person that gets it; my groupmates have the same code and it runs fine for them.

I've tried googling for the error. I didn't find any help as it is quite a specific one. Plus like i said my groupmates do not get this error. It is therefore probably not related to the code.

The error i get is this:

```<code>Error:Kotlin: [Internal Error] java.lang.IllegalStateException: Backend Internal error: Exception during code generation
Cause: Back-end (JVM) Internal error: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
Cause: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
File being compiled at position: (32,28) in C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: KotlinTypeMapper.java:116
File being compiled at position: file://C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: ExpressionCodegen.java:322
    at org.jetbrains.kotlin.codegen.CompilationErrorHandler.lambda$static$0(CompilationErrorHandler.java:24)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:74)
    at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generatePackage(CodegenFactory.kt:97)
    at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generateModule(CodegenFactory.kt:68)
    at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.doGenerateFiles(KotlinCodegenFacade.java:47)
    at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:39)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:446)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:142)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:161)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:57)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:96)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:52)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:93)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:402)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:101)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:937)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:101)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:977)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:936)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:400)
    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 java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
Cause: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
File being compiled at position: (32,28) in C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: KotlinTypeMapper.java:116
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:322)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:281)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:354)
    at org.jetbrains.kotlin.codegen.CallGenerator$DefaultCallGenerator.genValueAndPut(CallGenerator.kt:68)
    at org.jetbrains.kotlin.codegen.CallBasedArgumentGenerator.generateExpression(CallBasedArgumentGenerator.java:58)
    at org.jetbrains.kotlin.codegen.ArgumentGenerator.generate(ArgumentGenerator.kt:68)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.invokeMethodWithArguments(ExpressionCodegen.java:2461)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.invokeMethodWithArguments(ExpressionCodegen.java:2433)
    at org.jetbrains.kotlin.codegen.Callable$invokeMethodWithArguments$1.invoke(Callable.kt:41)
    at org.jetbrains.kotlin.codegen.Callable$invokeMethodWithArguments$1.invoke(Callable.kt:13)
    at org.jetbrains.kotlin.codegen.OperationStackValue.putSelector(StackValue.kt:79)
    at org.jetbrains.kotlin.codegen.StackValueWithLeaveTask.putSelector(StackValue.kt:67)
    at org.jetbrains.kotlin.codegen.StackValue.put(StackValue.java:112)
    at org.jetbrains.kotlin.codegen.StackValue.put(StackValue.java:101)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.putStackValue(ExpressionCodegen.java:378)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:363)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:358)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generateInitializers(MemberCodegen.java:493)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.generatePrimaryConstructorImpl(ConstructorCodegen.java:213)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.access$000(ConstructorCodegen.java:41)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen$1.doGenerateBody(ConstructorCodegen.java:97)
    at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy$CodegenBased.generateBody(FunctionGenerationStrategy.java:84)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:674)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:435)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:266)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.generatePrimaryConstructor(ConstructorCodegen.java:93)
    at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateConstructors(ImplementationBodyCodegen.java:462)
    at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:83)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:128)
    at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
    at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassOrObject(PackageCodegenImpl.java:161)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:86)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:119)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:66)
    ... 36 more
Caused by: java.lang.IllegalStateException: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$1.processErrorType(KotlinTypeMapper.java:116)
    at org.jetbrains.kotlin.load.kotlin.TypeSignatureMappingKt.mapType(typeSignatureMapping.kt:91)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapType(KotlinTypeMapper.java:512)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameterType(KotlinTypeMapper.java:1518)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameter(KotlinTypeMapper.java:1488)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameter(KotlinTypeMapper.java:1477)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.lambda$mapSignatureWithCustomParameters$4(KotlinTypeMapper.java:1295)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Collections$2.tryAdvance(Collections.java:4745)
    at java.base/java.util.Collections$2.forEachRemaining(Collections.java:4753)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignatureWithCustomParameters(KotlinTypeMapper.java:1293)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignature(KotlinTypeMapper.java:1212)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignatureWithGeneric(KotlinTypeMapper.java:1171)
    at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy.mapMethodSignature(FunctionGenerationStrategy.java:46)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:204)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:183)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateResumeImpl(CoroutineCodegen.kt:421)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateClosureBody(CoroutineCodegen.kt:234)
    at org.jetbrains.kotlin.codegen.ClosureCodegen.generateBody(ClosureCodegen.java:166)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateBody(CoroutineCodegen.kt:242)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:128)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genClosure(ExpressionCodegen.java:1022)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genClosure(ExpressionCodegen.java:992)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitLambdaExpression(ExpressionCodegen.java:983)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitLambdaExpression(ExpressionCodegen.java:111)
    at org.jetbrains.kotlin.psi.KtLambdaExpression.accept(KtLambdaExpression.java:39)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:299)
    ... 70 more
</code>```

I'm sure this has to do with my IDE or some local setting. Again, my groupmates don't get this error. The file that is mentioned in the error, EndRoundState.kt, however looks like this. If this helps clarify my problem.

```<code>package nl.han.asd.a1.network.networkstates

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import nl.han.asd.a1.network.NetworkLogic
import nl.han.asd.a1.network.Player
import nl.han.asd.a1.network.networkmessages.NetworkMessage
import nl.han.asd.a1.network.networkmessages.NetworkMessageTypes.*
import nl.han.asd.a1.network.networkmessages.messagetypes.GameData
import nl.han.asd.a1.utilities.gameclock.IClock

class EndRoundState(networkLogic: NetworkLogic, var players: MutableList<Player>, hash: String, val clock: IClock) : NetworkState(networkLogic) {

    private var rightstate = true
    private val endRoundDuration = 5000 //How long should the program be in this state? default = 5000
    private val checkTimerInterval = 500L //How often should we check if the timer has expired. default = 500L

    init {
        var hashes: MutableList<String> = mutableListOf()
        players.forEach {
            if (it.hash != null) {
                hashes.add(it.hash.toString())
            }
        }
        val rightHash = getRightHash(hashes)
        if (hash == rightHash) {
            this.networkLogic.correctGameState(hash)
        } else {
            rightstate = false
        }
        GlobalScope.launch {
            //launch a coroutine that will run alongside the other code. Think of it as a thread-lite. This will change the state after endRoundDuration expires
            val endTime: Long = clock.getCurrentTime() + endRoundDuration
            while (true) {
                delay(checkTimerInterval)
                if (clock.getCurrentTime() >= endTime) {
                    networkLogic.startNewRound()
                    return@launch
                }
            }
        }
    }

    override fun handleMessage(message: NetworkMessage, ip: String) {
        when (message.networkMessageType) {
            ROUND_IS_OVER -> ignore()
            CONNECT_REQUEST -> ignore()
            CONNECT_RESPONSE -> ignore()
            GAME_ANNOUNCE -> ignore()
            GAME_DATA -> {
                if (!rightstate) {
                    val gameData = message as GameData
                    this.networkLogic.setGameState(gameData.data.game)
                }
            }
            INITIATOR_MESSAGE -> ignore()
            MOVE -> TODO()
            RECONNECT_REQUEST -> TODO()
        }
    }

    private fun ignore() {

    }

    private fun getRightHash(hashes: MutableList<String>): String {
        val frequenciesByHash = hashes.groupingBy { it }.eachCount()
        var highestCount = 0
        var rightHash: String? = null
        frequenciesByHash.forEach {
            if (it.value > highestCount) {
                highestCount = it.value
                rightHash = it.key
            }
        }

        return run {if(rightHash.isNullOrEmpty()) "" else rightHash!!}
    }
}
</code>```

I just want the code to compile on my machine, like it does for my collegues. It does compile through Maven, just not through IntelliJ.

Thank you very much!

答:
I've encountered this in one of our test-cases where we had a function with a long name.
Granted this development machine was a Windows 10 machine, and Windows has a history of having problems with long filenames, https://community.spiceworks.com/topic/2006950-file-path-too-long-shortening-names-is-only-the-solution.

Try to see if the filename or the function names is too long and shorten it.
It certainly helped me to reduce the 93 character test function name to 70 characters.

Also check to see if you are using weird characters and emojis, some times they can mess up the file generation.

Have fun and be safe out there.

Body:
I'm part of a group that is developing a program in Kotlin. I have recently pulled fresh code off the development branch. The problem is i get this strange error. I am the only person that gets it; my groupmates have the same code and it runs fine for them.

I've tried googling for the error. I didn't find any help as it is quite a specific one. Plus like i said my groupmates do not get this error. It is therefore probably not related to the code.

The error i get is this:

Error:Kotlin: [Internal Error] java.lang.IllegalStateException: Backend Internal error: Exception during code generation
Cause: Back-end (JVM) Internal error: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
Cause: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
File being compiled at position: (32,28) in C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: KotlinTypeMapper.java:116
File being compiled at position: file://C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: ExpressionCodegen.java:322
    at org.jetbrains.kotlin.codegen.CompilationErrorHandler.lambda$static$0(CompilationErrorHandler.java:24)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:74)
    at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generatePackage(CodegenFactory.kt:97)
    at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generateModule(CodegenFactory.kt:68)
    at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.doGenerateFiles(KotlinCodegenFacade.java:47)
    at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:39)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:446)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:142)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:161)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:57)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:96)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:52)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:93)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:402)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$1.invoke(CompileServiceImpl.kt:101)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:937)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:101)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:977)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:936)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:400)
    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 java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
Cause: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
File being compiled at position: (32,28) in C:/Users/Gebruiker/Desktop/Repo/game/src/main/kotlin/nl/han/asd/a1/network/networkstates/EndRoundState.kt
The root cause was thrown at: KotlinTypeMapper.java:116
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:322)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:281)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:354)
    at org.jetbrains.kotlin.codegen.CallGenerator$DefaultCallGenerator.genValueAndPut(CallGenerator.kt:68)
    at org.jetbrains.kotlin.codegen.CallBasedArgumentGenerator.generateExpression(CallBasedArgumentGenerator.java:58)
    at org.jetbrains.kotlin.codegen.ArgumentGenerator.generate(ArgumentGenerator.kt:68)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.invokeMethodWithArguments(ExpressionCodegen.java:2461)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.invokeMethodWithArguments(ExpressionCodegen.java:2433)
    at org.jetbrains.kotlin.codegen.Callable$invokeMethodWithArguments$1.invoke(Callable.kt:41)
    at org.jetbrains.kotlin.codegen.Callable$invokeMethodWithArguments$1.invoke(Callable.kt:13)
    at org.jetbrains.kotlin.codegen.OperationStackValue.putSelector(StackValue.kt:79)
    at org.jetbrains.kotlin.codegen.StackValueWithLeaveTask.putSelector(StackValue.kt:67)
    at org.jetbrains.kotlin.codegen.StackValue.put(StackValue.java:112)
    at org.jetbrains.kotlin.codegen.StackValue.put(StackValue.java:101)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.putStackValue(ExpressionCodegen.java:378)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:363)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:358)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generateInitializers(MemberCodegen.java:493)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.generatePrimaryConstructorImpl(ConstructorCodegen.java:213)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.access$000(ConstructorCodegen.java:41)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen$1.doGenerateBody(ConstructorCodegen.java:97)
    at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy$CodegenBased.generateBody(FunctionGenerationStrategy.java:84)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:674)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:435)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:266)
    at org.jetbrains.kotlin.codegen.ConstructorCodegen.generatePrimaryConstructor(ConstructorCodegen.java:93)
    at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateConstructors(ImplementationBodyCodegen.java:462)
    at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:83)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:128)
    at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
    at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassOrObject(PackageCodegenImpl.java:161)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:86)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:119)
    at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:66)
    ... 36 more
Caused by: java.lang.IllegalStateException: Error type encountered: [ERROR : For SuccessOrFailure] (ErrorType).
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$1.processErrorType(KotlinTypeMapper.java:116)
    at org.jetbrains.kotlin.load.kotlin.TypeSignatureMappingKt.mapType(typeSignatureMapping.kt:91)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapType(KotlinTypeMapper.java:512)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameterType(KotlinTypeMapper.java:1518)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameter(KotlinTypeMapper.java:1488)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.writeParameter(KotlinTypeMapper.java:1477)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.lambda$mapSignatureWithCustomParameters$4(KotlinTypeMapper.java:1295)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Collections$2.tryAdvance(Collections.java:4745)
    at java.base/java.util.Collections$2.forEachRemaining(Collections.java:4753)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignatureWithCustomParameters(KotlinTypeMapper.java:1293)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignature(KotlinTypeMapper.java:1212)
    at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.mapSignatureWithGeneric(KotlinTypeMapper.java:1171)
    at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy.mapMethodSignature(FunctionGenerationStrategy.java:46)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:204)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:183)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateResumeImpl(CoroutineCodegen.kt:421)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateClosureBody(CoroutineCodegen.kt:234)
    at org.jetbrains.kotlin.codegen.ClosureCodegen.generateBody(ClosureCodegen.java:166)
    at org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenForLambda.generateBody(CoroutineCodegen.kt:242)
    at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:128)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genClosure(ExpressionCodegen.java:1022)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genClosure(ExpressionCodegen.java:992)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitLambdaExpression(ExpressionCodegen.java:983)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitLambdaExpression(ExpressionCodegen.java:111)
    at org.jetbrains.kotlin.psi.KtLambdaExpression.accept(KtLambdaExpression.java:39)
    at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:299)
    ... 70 more

I'm sure this has to do with my IDE or some local setting. Again, my groupmates don't get this error. The file that is mentioned in the error, EndRoundState.kt, however looks like this. If this helps clarify my problem.

package nl.han.asd.a1.network.networkstates

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import nl.han.asd.a1.network.NetworkLogic
import nl.han.asd.a1.network.Player
import nl.han.asd.a1.network.networkmessages.NetworkMessage
import nl.han.asd.a1.network.networkmessages.NetworkMessageTypes.*
import nl.han.asd.a1.network.networkmessages.messagetypes.GameData
import nl.han.asd.a1.utilities.gameclock.IClock

class EndRoundState(networkLogic: NetworkLogic, var players: MutableList<Player>, hash: String, val clock: IClock) : NetworkState(networkLogic) {

    private var rightstate = true
    private val endRoundDuration = 5000 //How long should the program be in this state? default = 5000
    private val checkTimerInterval = 500L //How often should we check if the timer has expired. default = 500L

    init {
        var hashes: MutableList<String> = mutableListOf()
        players.forEach {
            if (it.hash != null) {
                hashes.add(it.hash.toString())
            }
        }
        val rightHash = getRightHash(hashes)
        if (hash == rightHash) {
            this.networkLogic.correctGameState(hash)
        } else {
            rightstate = false
        }
        GlobalScope.launch {
            //launch a coroutine that will run alongside the other code. Think of it as a thread-lite. This will change the state after endRoundDuration expires
            val endTime: Long = clock.getCurrentTime() + endRoundDuration
            while (true) {
                delay(checkTimerInterval)
                if (clock.getCurrentTime() >= endTime) {
                    networkLogic.startNewRound()
                    return@launch
                }
            }
        }
    }

    override fun handleMessage(message: NetworkMessage, ip: String) {
        when (message.networkMessageType) {
            ROUND_IS_OVER -> ignore()
            CONNECT_REQUEST -> ignore()
            CONNECT_RESPONSE -> ignore()
            GAME_ANNOUNCE -> ignore()
            GAME_DATA -> {
                if (!rightstate) {
                    val gameData = message as GameData
                    this.networkLogic.setGameState(gameData.data.game)
                }
            }
            INITIATOR_MESSAGE -> ignore()
            MOVE -> TODO()
            RECONNECT_REQUEST -> TODO()
        }
    }

    private fun ignore() {

    }

    private fun getRightHash(hashes: MutableList<String>): String {
        val frequenciesByHash = hashes.groupingBy { it }.eachCount()
        var highestCount = 0
        var rightHash: String? = null
        frequenciesByHash.forEach {
            if (it.value > highestCount) {
                highestCount = it.value
                rightHash = it.key
            }
        }

        return run {if(rightHash.isNullOrEmpty()) "" else rightHash!!}
    }
}

I just want the code to compile on my machine, like it does for my collegues. It does compile through Maven, just not through IntelliJ.

Thank you very much!


问:
Trouble mapping json to golang struct
I have a json stream as follows ...

```<code>[
  {
    "page": 1,
    "pages": 7,
    "per_page": "2000",
    "total": 13200
  },
  [
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": null,
      "decimal": "0",
      "date": "2019"
    },
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": "419790588",
      "decimal": "0",
      "date": "2018"
    },
   ...
   ]
]
</code>```

And I'm trying to decode it ... so I have the following struct ... but I keep getting
"cannot unmarshal array into Go value of type struct { P struct ... "

```<code>type Message []struct {
        P struct {
                Page int
        }
        V []struct {
                Indicator struct {
                        Id    string
                        Value string
                }
                Country struct {
                        Value string
                }
                Value   string
                Decimal string
                Date    string
        }
}
</code>```

My struct looks to match the json ... but obviously not! Any ideas?

答:
Since your JSON array have two different types first unmarshal them into a slice of json.RawMessage which is []byte as underlying type so that we can unmarshal again JSON array data.

So unmarshal data for P and V struct type using index directly (predict) or detect if object(starting with '{') then unmarshal into P and array(starting with '[') then unmarshal into  V. Now prepare your Message using those data.

```<code>type Message struct {
    PageData P
    ValData  []V
}

type P struct {
    Page int
}

type V struct {
    Indicator struct {
        Id    string
        Value string
    }
    Country struct {
        Value string
    }
    Value   string
    Decimal string
    Date    string
}

func main() {

    var rawdata []json.RawMessage
    json.Unmarshal([]byte(jsonData), &rawdata)
    var pageData P
    json.Unmarshal(rawdata[0], &pageData)
    var valData []V
    json.Unmarshal(rawdata[1], &valData)
    res := Message{pageData, valData}
    fmt.Println(res)
}
var jsonData = `[...]` //your json data
</code>```

Full code in Go Playground

Title: Trouble mapping json to golang struct

Body:
I have a json stream as follows ...

[
  {
    "page": 1,
    "pages": 7,
    "per_page": "2000",
    "total": 13200
  },
  [
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": null,
      "decimal": "0",
      "date": "2019"
    },
    {
      "indicator": {
        "id": "SP.POP.TOTL",
        "value": "Population, total"
      },
      "country": {
        "id": "1A",
        "value": "Arab World"
      },
      "value": "419790588",
      "decimal": "0",
      "date": "2018"
    },
   ...
   ]
]

And I'm trying to decode it ... so I have the following struct ... but I keep getting
"cannot unmarshal array into Go value of type struct { P struct ... "

type Message []struct {
        P struct {
                Page int
        }
        V []struct {
                Indicator struct {
                        Id    string
                        Value string
                }
                Country struct {
                        Value string
                }
                Value   string
                Decimal string
                Date    string
        }
}

My struct looks to match the json ... but obviously not! Any ideas?

Body:
Since your JSON array have two different types first unmarshal them into a slice of json.RawMessage which is []byte as underlying type so that we can unmarshal again JSON array data.

So unmarshal data for P and V struct type using index directly (predict) or detect if object(starting with '{') then unmarshal into P and array(starting with '[') then unmarshal into  V. Now prepare your Message using those data.

type Message struct {
    PageData P
    ValData  []V
}

type P struct {
    Page int
}

type V struct {
    Indicator struct {
        Id    string
        Value string
    }
    Country struct {
        Value string
    }
    Value   string
    Decimal string
    Date    string
}

func main() {

    var rawdata []json.RawMessage
    json.Unmarshal([]byte(jsonData), &rawdata)
    var pageData P
    json.Unmarshal(rawdata[0], &pageData)
    var valData []V
    json.Unmarshal(rawdata[1], &valData)
    res := Message{pageData, valData}
    fmt.Println(res)
}
var jsonData = `[...]` //your json data

Full code in Go Playground


问:
Equivalent version of SHA256 ComputeHash (from C#) for React Native/JS
I'm trying to build an equivalent version of SHA256 ComputeHash (from C#, the EXACT same output from the below sample), to React Native/JavaScript.
This is the following C#:

```<code>public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.Unicode.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}
</code>```

I tried the following, but it doesn't generate the same Hash:

```<code>import * as Crypto from 'expo-crypto';

const hash = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    "StringIWantToHash"
);
</code>```

Would anyone know, either what's wrong with the JavaScript, or if there is an exact equivalent version of the C# one?

答:
Expo React Native:

Solution 1:
install sha256 by

```<code>yarn add sha256
</code>```

```<code>import React, { Component } from "react";
import { Text, StyleSheet, View } from "react-native";
const sha256 = require("sha256");

const isNullOrWhitespace = (input) => {
  if (typeof input === "undefined" || input == null) return true;
  return input.replace(/\s/g, "").length < 1;
};

const getByteArray = (input) => {
  let bytes = [];
  for (var i = 0, k = 0; i < input.length; i++, k += 2) {
    bytes[k] = input.charCodeAt(i);
    bytes[k + 1] = 0;
  }
  return bytes;
};

const hash = async (input) => {
  if (isNullOrWhitespace(input)) {
    return "";
  }
  var bytes = getByteArray(input);
  const hashString = "0x" + sha256(bytes, { asBytes: false });
  return hashString;
};

export default class App extends Component {
  state = {
    encodedString: "",
  };
  async UNSAFE_componentWillMount() {
    const encodedString = await hash("test2"); //0x39a2272982dc7e6e5d109ab36ec280f6cd3b4b7440af5c739ed808d4ec02aae4
    this.setState({ encodedString: encodedString });
  }
  render() {
    const { encodedString } = this.state;
    return (
      <View style={styles.container}>
        <Text>{encodedString}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});
</code>```

Solution 2:

you are using ToString("X2") in c# which means you have to convert hash to HEX (base 16)

here id demo: https://snack.expo.io/@nomi9995/expo-crypto

you need to convert hash to HEX (base 16) like this

```<code>await hash.toString(16);
</code>```

try this it will give the same result as c#

Code :

```<code>  import React, { Component } from "react";
  import { Text, StyleSheet, View } from "react-native";

  import * as Crypto from "expo-crypto";

  const isNullOrWhitespace = (input) => {
    if (typeof input === "undefined" || input == null) return true;
    return input.replace(/\s/g, "").length < 1;
  };

  const hash = async (input) => {
    if (isNullOrWhitespace(input)) {
      return "";
    }
    let hash = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.SHA256,
      input
    );
    const sBuilder = await hash.toString(16);

    return `0x${sBuilder.toLowerCase()}`;
  };

  export default class App extends Component {
    state = {
      encodedString: "",
    };
    async UNSAFE_componentWillMount() {
      const result = await hash("StringIWantToHash"); //here you can pass your string
      this.setState({ encodedString: result });
    }
    render() {
      const { encodedString } = this.state;
      return (
        <View style={styles.container}>
          <Text>{encodedString}</Text>
        </View>
      );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: "center",
      alignItems: "center",
    },
  });
</code>```

Node js:

install crypto-js by

```<code>yarn add crypto-js
</code>```

try this it will give the same result as c#

```<code>var CryptoJS = require("crypto-js");

const isNullOrWhitespace = (input) => {
  if (typeof input === "undefined" || input == null) return true;
  return input.replace(/\s/g, "").length < 1;
};

const hash = (input) => {
  if (isNullOrWhitespace(input)) {
    return "";
  }
  let hash = CryptoJS.SHA256(input);
  const sBuilder=hash.toString(CryptoJS.enc.Hex);

  return `0x${sBuilder.toLowerCase()}`;
};

const result=hash("StringIWantToHash");
console.log(result,"result"); // it will give the same result as C#
</code>```

Body:
I'm trying to build an equivalent version of SHA256 ComputeHash (from C#, the EXACT same output from the below sample), to React Native/JavaScript.
This is the following C#:

public static string Hash(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return "";

    using (SHA256 hasher = SHA256.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = hasher.ComputeHash(Encoding.Unicode.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("X2"));
        }

        // Return the hexadecimal string.
        return $"0x{sBuilder.ToString().ToLower()}";
    }
}

I tried the following, but it doesn't generate the same Hash:

import * as Crypto from 'expo-crypto';

const hash = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    "StringIWantToHash"
);

Would anyone know, either what's wrong with the JavaScript, or if there is an exact equivalent version of the C# one?

Body:
Expo React Native:

Solution 1:
install sha256 by

yarn add sha256

import React, { Component } from "react";
import { Text, StyleSheet, View } from "react-native";
const sha256 = require("sha256");

const isNullOrWhitespace = (input) => {
  if (typeof input === "undefined" || input == null) return true;
  return input.replace(/\s/g, "").length < 1;
};

const getByteArray = (input) => {
  let bytes = [];
  for (var i = 0, k = 0; i < input.length; i++, k += 2) {
    bytes[k] = input.charCodeAt(i);
    bytes[k + 1] = 0;
  }
  return bytes;
};

const hash = async (input) => {
  if (isNullOrWhitespace(input)) {
    return "";
  }
  var bytes = getByteArray(input);
  const hashString = "0x" + sha256(bytes, { asBytes: false });
  return hashString;
};

export default class App extends Component {
  state = {
    encodedString: "",
  };
  async UNSAFE_componentWillMount() {
    const encodedString = await hash("test2"); //0x39a2272982dc7e6e5d109ab36ec280f6cd3b4b7440af5c739ed808d4ec02aae4
    this.setState({ encodedString: encodedString });
  }
  render() {
    const { encodedString } = this.state;
    return (
      <View style={styles.container}>
        <Text>{encodedString}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

Solution 2:

you are using ToString("X2") in c# which means you have to convert hash to HEX (base 16)

here id demo: https://snack.expo.io/@nomi9995/expo-crypto

you need to convert hash to HEX (base 16) like this

await hash.toString(16);

try this it will give the same result as c#

Code :

  import React, { Component } from "react";
  import { Text, StyleSheet, View } from "react-native";

  import * as Crypto from "expo-crypto";

  const isNullOrWhitespace = (input) => {
    if (typeof input === "undefined" || input == null) return true;
    return input.replace(/\s/g, "").length < 1;
  };

  const hash = async (input) => {
    if (isNullOrWhitespace(input)) {
      return "";
    }
    let hash = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.SHA256,
      input
    );
    const sBuilder = await hash.toString(16);

    return `0x${sBuilder.toLowerCase()}`;
  };

  export default class App extends Component {
    state = {
      encodedString: "",
    };
    async UNSAFE_componentWillMount() {
      const result = await hash("StringIWantToHash"); //here you can pass your string
      this.setState({ encodedString: result });
    }
    render() {
      const { encodedString } = this.state;
      return (
        <View style={styles.container}>
          <Text>{encodedString}</Text>
        </View>
      );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: "center",
      alignItems: "center",
    },
  });

Node js:

install crypto-js by

yarn add crypto-js

try this it will give the same result as c#

var CryptoJS = require("crypto-js");

const isNullOrWhitespace = (input) => {
  if (typeof input === "undefined" || input == null) return true;
  return input.replace(/\s/g, "").length < 1;
};

const hash = (input) => {
  if (isNullOrWhitespace(input)) {
    return "";
  }
  let hash = CryptoJS.SHA256(input);
  const sBuilder=hash.toString(CryptoJS.enc.Hex);

  return `0x${sBuilder.toLowerCase()}`;
};

const result=hash("StringIWantToHash");
console.log(result,"result"); // it will give the same result as C#


问:
Why String.toDouble() will increase decimal places?
I have a server returning a value (in JSON) which contains a number with decimal places, e.g. 203.14.

Since in my app I need to do some calculation, I have to convert it to Double.

However when it is converted to Double, it's value becomes 203.13999938964844.

For some business logic reason, when I display this value, I need to round down this number to 2 decimal places.

So now it becomes 203.13, which is 0.01 smaller than the value server returns.

How can I preserve 203.14 when I convert "203.14" to Double?

Update:

I just found that the reason is because the model class used float to accept the server value, but then later converted to Double. If day one the model class uses double to accept the value, then the problem above will not exist.

答:
It appears to me that the number's real value is 203.1399999999999, but when you are outputting the data, the String format is rounding it to 203.14. If this is the case, then try to round the number before converting it to a Double.

If that doesn't work, try using either of the following methods instead of the one that you are currently using:
Double.parseDouble()
Double.valueOf()